<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>Python啃书笔记 | SongKaBaKa</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="笔记">
    <meta name="description" content="[TOC] 变量和简单数据类型字符串使用方法修改字符串的大小写 title() 该方法实现了单词首字母大写输出，例如姓名之间有空格会被识别为两个单词 upper() 该方法实现了全部字母大写输出 lower() 该方法实现了全部字母小写输出  合并（拼接）字符串v1+“ ”+v2 如果字符串与整型变量拼接的话，会出现类型错误，可以使用str()函数将整型变量格式化为字符串，防止歧义发生 使用制表符">
<meta property="og:type" content="article">
<meta property="og:title" content="Python啃书笔记">
<meta property="og:url" content="https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/index.html">
<meta property="og:site_name" content="SongKaBaKa">
<meta property="og:description" content="[TOC] 变量和简单数据类型字符串使用方法修改字符串的大小写 title() 该方法实现了单词首字母大写输出，例如姓名之间有空格会被识别为两个单词 upper() 该方法实现了全部字母大写输出 lower() 该方法实现了全部字母小写输出  合并（拼接）字符串v1+“ ”+v2 如果字符串与整型变量拼接的话，会出现类型错误，可以使用str()函数将整型变量格式化为字符串，防止歧义发生 使用制表符">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-07-10T07:20:36.000Z">
<meta property="article:modified_time" content="2020-07-29T05:45:35.549Z">
<meta property="article:author" content="Song Wani">
<meta property="article:tag" content="笔记">
<meta name="twitter:card" content="summary">
    
    <link rel="shortcut icon" href="/blog/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

<meta name="generator" content="Hexo 4.2.1"></head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/brand.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">Song Wani</h5>
          <a href="mailto:bugsong@wo.cn" title="bugsong@wo.cn" class="mail">bugsong@wo.cn</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://songbug.gitee.io/blog" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Python啃书笔记</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="Search">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Python啃书笔记</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-07-10T07:20:36.000Z" itemprop="datePublished" class="page-time">
  2020-07-10
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E7%BC%96%E7%A8%8B/">编程</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#变量和简单数据类型"><span class="post-toc-number">1.</span> <span class="post-toc-text">变量和简单数据类型</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#字符串"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">字符串</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用方法修改字符串的大小写"><span class="post-toc-number">1.1.1.</span> <span class="post-toc-text">使用方法修改字符串的大小写</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#合并（拼接）字符串"><span class="post-toc-number">1.1.2.</span> <span class="post-toc-text">合并（拼接）字符串</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用制表符或换行符来添加空白"><span class="post-toc-number">1.1.3.</span> <span class="post-toc-text">使用制表符或换行符来添加空白</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#删除空白"><span class="post-toc-number">1.1.4.</span> <span class="post-toc-text">删除空白</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#数字"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">数字</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#整数"><span class="post-toc-number">1.2.1.</span> <span class="post-toc-text">整数</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#浮点数"><span class="post-toc-number">1.2.2.</span> <span class="post-toc-text">浮点数</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用函数str-避免类型错误"><span class="post-toc-number">1.2.3.</span> <span class="post-toc-text">使用函数str()避免类型错误</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#注释"><span class="post-toc-number">1.2.4.</span> <span class="post-toc-text">注释</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Python之禅"><span class="post-toc-number">1.2.5.</span> <span class="post-toc-text">Python之禅</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#小结"><span class="post-toc-number">1.2.6.</span> <span class="post-toc-text">小结</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#列表简介"><span class="post-toc-number">2.</span> <span class="post-toc-text">列表简介</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#列表是什么"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">列表是什么</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#访问列表元素"><span class="post-toc-number">2.1.1.</span> <span class="post-toc-text">访问列表元素</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#修改、添加和删除元素"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">修改、添加和删除元素</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#修改列表元素"><span class="post-toc-number">2.2.1.</span> <span class="post-toc-text">修改列表元素</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#在列表中添加元素"><span class="post-toc-number">2.2.2.</span> <span class="post-toc-text">在列表中添加元素</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#从列表中删除元素"><span class="post-toc-number">2.2.3.</span> <span class="post-toc-text">从列表中删除元素</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#组织列表"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">组织列表</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用sort-方法对列表进行永久性排序"><span class="post-toc-number">2.3.1.</span> <span class="post-toc-text">使用sort()方法对列表进行永久性排序</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用sorted-函数对列表进行临时排序"><span class="post-toc-number">2.3.2.</span> <span class="post-toc-text">使用sorted()函数对列表进行临时排序</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#倒着打印列表"><span class="post-toc-number">2.3.3.</span> <span class="post-toc-text">倒着打印列表</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#确定列表的长度"><span class="post-toc-number">2.3.3.1.</span> <span class="post-toc-text">确定列表的长度</span></a></li></ol></li></ol></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#操作列表"><span class="post-toc-number">3.</span> <span class="post-toc-text">操作列表</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#遍历整个列表"><span class="post-toc-number">3.1.</span> <span class="post-toc-text">遍历整个列表</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#深入研究循环"><span class="post-toc-number">3.1.1.</span> <span class="post-toc-text">深入研究循环</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#避免出现缩进问题，不可遗漏冒号"><span class="post-toc-number">3.1.2.</span> <span class="post-toc-text">避免出现缩进问题，不可遗漏冒号</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#创建数值列表"><span class="post-toc-number">3.2.</span> <span class="post-toc-text">创建数值列表</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用list-创建数字列表"><span class="post-toc-number">3.2.1.</span> <span class="post-toc-text">使用list()创建数字列表</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#对数字列表执行简单的统计计算"><span class="post-toc-number">3.2.2.</span> <span class="post-toc-text">对数字列表执行简单的统计计算</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#列表解析"><span class="post-toc-number">3.3.</span> <span class="post-toc-text">列表解析</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#使用列表的一部分"><span class="post-toc-number">3.4.</span> <span class="post-toc-text">使用列表的一部分</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#切片"><span class="post-toc-number">3.4.1.</span> <span class="post-toc-text">切片</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#遍历切片"><span class="post-toc-number">3.4.2.</span> <span class="post-toc-text">遍历切片</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#复制列表"><span class="post-toc-number">3.4.3.</span> <span class="post-toc-text">复制列表</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#元组"><span class="post-toc-number">3.5.</span> <span class="post-toc-text">元组</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#if语句"><span class="post-toc-number">4.</span> <span class="post-toc-text">if语句</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#条件测试"><span class="post-toc-number">4.0.1.</span> <span class="post-toc-text">条件测试</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#if-else语句"><span class="post-toc-number">4.1.</span> <span class="post-toc-text">if-else语句</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#if-elif-else"><span class="post-toc-number">4.2.</span> <span class="post-toc-text">if-elif-else</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#多个elif，与else的省略"><span class="post-toc-number">4.2.1.</span> <span class="post-toc-text">多个elif，与else的省略</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#for-in设置两个可迭代对象"><span class="post-toc-number">4.3.</span> <span class="post-toc-text">for-in设置两个可迭代对象</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#字典（dictionary）"><span class="post-toc-number">5.</span> <span class="post-toc-text">字典（dictionary）</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#一个简单的字典"><span class="post-toc-number">5.1.</span> <span class="post-toc-text">一个简单的字典</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#使用字典"><span class="post-toc-number">5.2.</span> <span class="post-toc-text">使用字典</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#添加键-值对"><span class="post-toc-number">5.2.1.</span> <span class="post-toc-text">添加键-值对</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#修改字典中的值"><span class="post-toc-number">5.2.2.</span> <span class="post-toc-text">修改字典中的值</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#删除键-值对"><span class="post-toc-number">5.2.3.</span> <span class="post-toc-text">删除键-值对</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#由类似对象组成的字典"><span class="post-toc-number">5.2.4.</span> <span class="post-toc-text">由类似对象组成的字典</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#遍历字典"><span class="post-toc-number">5.3.</span> <span class="post-toc-text">遍历字典</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#for循环遍历字典的方式"><span class="post-toc-number">5.3.1.</span> <span class="post-toc-text">for循环遍历字典的方式</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#遍历字典中的键"><span class="post-toc-number">5.3.2.</span> <span class="post-toc-text">遍历字典中的键</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#按顺序遍历字典中所有的键"><span class="post-toc-number">5.3.3.</span> <span class="post-toc-text">按顺序遍历字典中所有的键</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#遍历字典中所有的值"><span class="post-toc-number">5.3.4.</span> <span class="post-toc-text">遍历字典中所有的值</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#嵌套"><span class="post-toc-number">5.4.</span> <span class="post-toc-text">嵌套</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#字典列表"><span class="post-toc-number">5.4.1.</span> <span class="post-toc-text">字典列表</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#字典中存储列表"><span class="post-toc-number">5.4.2.</span> <span class="post-toc-text">字典中存储列表</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#字典中存储字典"><span class="post-toc-number">5.4.3.</span> <span class="post-toc-text">字典中存储字典</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#用户输入和while循环"><span class="post-toc-number">6.</span> <span class="post-toc-text">用户输入和while循环</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#函数-input-工作原理"><span class="post-toc-number">6.1.</span> <span class="post-toc-text">函数 input() 工作原理</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#参数"><span class="post-toc-number">6.2.</span> <span class="post-toc-text">参数</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#类型转换"><span class="post-toc-number">6.3.</span> <span class="post-toc-text">类型转换</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#求模运算符"><span class="post-toc-number">6.4.</span> <span class="post-toc-text">求模运算符</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#使用标志"><span class="post-toc-number">6.5.</span> <span class="post-toc-text">使用标志</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#break与continue的使用"><span class="post-toc-number">6.6.</span> <span class="post-toc-text">break与continue的使用</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#使用while循环来处理列表和字典"><span class="post-toc-number">6.7.</span> <span class="post-toc-text">使用while循环来处理列表和字典</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#在列表之间移动元素"><span class="post-toc-number">6.7.1.</span> <span class="post-toc-text">在列表之间移动元素</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#结合remove-方法删除重复元素"><span class="post-toc-number">6.7.2.</span> <span class="post-toc-text">结合remove()方法删除重复元素</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用用户输入来填充字典"><span class="post-toc-number">6.7.3.</span> <span class="post-toc-text">使用用户输入来填充字典</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#函数"><span class="post-toc-number">7.</span> <span class="post-toc-text">函数</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#定义函数"><span class="post-toc-number">7.1.</span> <span class="post-toc-text">定义函数</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#向函数传递信息"><span class="post-toc-number">7.1.1.</span> <span class="post-toc-text">向函数传递信息</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#实参和形参"><span class="post-toc-number">7.1.2.</span> <span class="post-toc-text">实参和形参</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#传递实参"><span class="post-toc-number">7.2.</span> <span class="post-toc-text">传递实参</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#位置实参-大概就是尽量使用基于实参位置对应的形参"><span class="post-toc-number">7.2.1.</span> <span class="post-toc-text">位置实参(大概就是尽量使用基于实参位置对应的形参)</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#关键字实参"><span class="post-toc-number">7.2.2.</span> <span class="post-toc-text">关键字实参</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#默认值-指的是形参没给值，就用这个默认值"><span class="post-toc-number">7.2.3.</span> <span class="post-toc-text">默认值(指的是形参没给值，就用这个默认值)</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#等效的函数调用"><span class="post-toc-number">7.2.4.</span> <span class="post-toc-text">等效的函数调用</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#返回值"><span class="post-toc-number">7.3.</span> <span class="post-toc-text">返回值</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#返回简单值"><span class="post-toc-number">7.3.1.</span> <span class="post-toc-text">返回简单值</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#让实参变成可选的"><span class="post-toc-number">7.3.2.</span> <span class="post-toc-text">让实参变成可选的</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#返回字典"><span class="post-toc-number">7.3.3.</span> <span class="post-toc-text">返回字典</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#结合使用函数和while循环"><span class="post-toc-number">7.3.4.</span> <span class="post-toc-text">结合使用函数和while循环</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#传递列表"><span class="post-toc-number">7.4.</span> <span class="post-toc-text">传递列表</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#禁止函数修改源列表，使用副本传入"><span class="post-toc-number">7.4.1.</span> <span class="post-toc-text">禁止函数修改源列表，使用副本传入</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#传递任意数量的实参"><span class="post-toc-number">7.5.</span> <span class="post-toc-text">传递任意数量的实参</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用任意数量的关键字实参"><span class="post-toc-number">7.5.1.</span> <span class="post-toc-text">使用任意数量的关键字实参</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#将函数存储在模块中"><span class="post-toc-number">7.6.</span> <span class="post-toc-text">将函数存储在模块中</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#导入整个模块，使用函数须加模块名"><span class="post-toc-number">7.6.1.</span> <span class="post-toc-text">导入整个模块，使用函数须加模块名</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#导入特定的函数，调用直接用"><span class="post-toc-number">7.6.2.</span> <span class="post-toc-text">导入特定的函数，调用直接用</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用-as-给函数、模块指定别名"><span class="post-toc-number">7.6.3.</span> <span class="post-toc-text">使用 as 给函数、模块指定别名</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#到入模块中的所有函数，直接用"><span class="post-toc-number">7.6.4.</span> <span class="post-toc-text">到入模块中的所有函数，直接用</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#函数编写指南与章末小结"><span class="post-toc-number">7.7.</span> <span class="post-toc-text">函数编写指南与章末小结</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#类"><span class="post-toc-number">8.</span> <span class="post-toc-text">类</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#创建类和使用类"><span class="post-toc-number">8.1.</span> <span class="post-toc-text">创建类和使用类</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#创建Dog类"><span class="post-toc-number">8.1.1.</span> <span class="post-toc-text">创建Dog类</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#1-方法-init"><span class="post-toc-number">8.1.1.1.</span> <span class="post-toc-text">1.方法_ _ init _ _()</span></a></li></ol></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#根据类创建实例（instance，n，实例）"><span class="post-toc-number">8.1.2.</span> <span class="post-toc-text">根据类创建实例（instance，n，实例）</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#1-访问属性"><span class="post-toc-number">8.1.2.1.</span> <span class="post-toc-text">1.访问属性</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#2-调用方法"><span class="post-toc-number">8.1.2.2.</span> <span class="post-toc-text">2.调用方法</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#3-创建多个实例"><span class="post-toc-number">8.1.2.3.</span> <span class="post-toc-text">3.创建多个实例</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#使用类和实例"><span class="post-toc-number">8.2.</span> <span class="post-toc-text">使用类和实例</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Car类"><span class="post-toc-number">8.2.1.</span> <span class="post-toc-text">Car类</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#给属性指定默认值"><span class="post-toc-number">8.2.2.</span> <span class="post-toc-text">给属性指定默认值</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#修改属性的值"><span class="post-toc-number">8.2.3.</span> <span class="post-toc-text">修改属性的值</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#1-直接修改属性的值"><span class="post-toc-number">8.2.3.1.</span> <span class="post-toc-text">1.直接修改属性的值</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#2-通过方法修改"><span class="post-toc-number">8.2.3.2.</span> <span class="post-toc-text">2.通过方法修改</span></a></li><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#3-通过方法对属性的值进行递增"><span class="post-toc-number">8.2.3.3.</span> <span class="post-toc-text">3.通过方法对属性的值进行递增</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#继承"><span class="post-toc-number">8.3.</span> <span class="post-toc-text">继承</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#子类的方法-init"><span class="post-toc-number">8.3.1.</span> <span class="post-toc-text">子类的方法 _ _ init _ _ ()</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#给子类定义属性和方法"><span class="post-toc-number">8.3.2.</span> <span class="post-toc-text">给子类定义属性和方法</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#重写父类方法"><span class="post-toc-number">8.3.3.</span> <span class="post-toc-text">重写父类方法</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#将实例用作属性"><span class="post-toc-number">8.3.4.</span> <span class="post-toc-text">将实例用作属性</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#模拟实物"><span class="post-toc-number">8.3.5.</span> <span class="post-toc-text">模拟实物</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#导入类"><span class="post-toc-number">8.4.</span> <span class="post-toc-text">导入类</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#导入单个类"><span class="post-toc-number">8.4.1.</span> <span class="post-toc-text">导入单个类</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#在一个模块中存储多个类"><span class="post-toc-number">8.4.2.</span> <span class="post-toc-text">在一个模块中存储多个类</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#从一个模块中导入多个类，访问类直接用"><span class="post-toc-number">8.4.3.</span> <span class="post-toc-text">从一个模块中导入多个类，访问类直接用</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#导入整个模块，访问类须加模块名"><span class="post-toc-number">8.4.4.</span> <span class="post-toc-text">导入整个模块，访问类须加模块名</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#导入模块中的所有类"><span class="post-toc-number">8.4.5.</span> <span class="post-toc-text">导入模块中的所有类</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#在一个模块中导入另一个模块"><span class="post-toc-number">8.4.6.</span> <span class="post-toc-text">在一个模块中导入另一个模块</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#自定义工作流程"><span class="post-toc-number">8.4.7.</span> <span class="post-toc-text">自定义工作流程</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Python标准库"><span class="post-toc-number">8.5.</span> <span class="post-toc-text">Python标准库</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#类编码风格"><span class="post-toc-number">8.6.</span> <span class="post-toc-text">类编码风格</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#小结-1"><span class="post-toc-number">8.7.</span> <span class="post-toc-text">小结</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#文件和异常"><span class="post-toc-number">9.</span> <span class="post-toc-text">文件和异常</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#从文件中读取数据"><span class="post-toc-number">9.1.</span> <span class="post-toc-text">从文件中读取数据</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#读取整个文件"><span class="post-toc-number">9.1.1.</span> <span class="post-toc-text">读取整个文件</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-5"><a class="post-toc-link" href="#文件路径"><span class="post-toc-number">9.1.1.1.</span> <span class="post-toc-text">文件路径</span></a></li></ol></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#逐行读取"><span class="post-toc-number">9.1.2.</span> <span class="post-toc-text">逐行读取</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#创建一个包含文件行内容的列表"><span class="post-toc-number">9.1.3.</span> <span class="post-toc-text">创建一个包含文件行内容的列表</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#包含1-000-000位的大文件"><span class="post-toc-number">9.1.4.</span> <span class="post-toc-text">包含1,000,000位的大文件</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#圆周率中包含你的生日吗"><span class="post-toc-number">9.1.5.</span> <span class="post-toc-text">圆周率中包含你的生日吗</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#写入文件"><span class="post-toc-number">9.2.</span> <span class="post-toc-text">写入文件</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#写入空文件-write-方法"><span class="post-toc-number">9.2.1.</span> <span class="post-toc-text">写入空文件 write() 方法</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#异常"><span class="post-toc-number">9.3.</span> <span class="post-toc-text">异常</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#处理ZeroDivisionError（零除错误）"><span class="post-toc-number">9.3.1.</span> <span class="post-toc-text">处理ZeroDivisionError（零除错误）</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用-try-except-代码块"><span class="post-toc-number">9.3.2.</span> <span class="post-toc-text">使用 try-except 代码块</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#else代码块"><span class="post-toc-number">9.3.3.</span> <span class="post-toc-text">else代码块</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#处理FileNotFoundError异常"><span class="post-toc-number">9.3.4.</span> <span class="post-toc-text">处理FileNotFoundError异常</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#分析文本"><span class="post-toc-number">9.3.5.</span> <span class="post-toc-text">分析文本</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用多个文件"><span class="post-toc-number">9.3.6.</span> <span class="post-toc-text">使用多个文件</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#失败时不吭一声"><span class="post-toc-number">9.3.7.</span> <span class="post-toc-text">失败时不吭一声</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#决定报告那些错误"><span class="post-toc-number">9.3.8.</span> <span class="post-toc-text">决定报告那些错误</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#存储数据"><span class="post-toc-number">9.4.</span> <span class="post-toc-text">存储数据</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用json-dump-和-json-load"><span class="post-toc-number">9.4.1.</span> <span class="post-toc-text">使用json.dump() 和 json.load()</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#保存和读取用户生成的数据"><span class="post-toc-number">9.4.2.</span> <span class="post-toc-text">保存和读取用户生成的数据</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#重构"><span class="post-toc-number">9.4.3.</span> <span class="post-toc-text">重构</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#测试代码"><span class="post-toc-number">10.</span> <span class="post-toc-text">测试代码</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试函数"><span class="post-toc-number">10.1.</span> <span class="post-toc-text">测试函数</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#可通过的测试"><span class="post-toc-number">10.1.1.</span> <span class="post-toc-text">可通过的测试</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#测试未通过时怎么办"><span class="post-toc-number">10.1.2.</span> <span class="post-toc-text">测试未通过时怎么办</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#添加新测试"><span class="post-toc-number">10.1.3.</span> <span class="post-toc-text">添加新测试</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试类"><span class="post-toc-number">10.2.</span> <span class="post-toc-text">测试类</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#各种断言方法"><span class="post-toc-number">10.2.1.</span> <span class="post-toc-text">各种断言方法</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#一个要测试的类"><span class="post-toc-number">10.2.2.</span> <span class="post-toc-text">一个要测试的类</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#测试这个AnonymousSurvey类"><span class="post-toc-number">10.2.3.</span> <span class="post-toc-text">测试这个AnonymousSurvey类</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#unittest的另一项功能，方法setUp"><span class="post-toc-number">10.2.4.</span> <span class="post-toc-text">unittest的另一项功能，方法setUp()</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#小结-2"><span class="post-toc-number">10.2.5.</span> <span class="post-toc-text">小结</span></a></li></ol></li></ol></li></ol>
        </nav>
    </aside>


<article id="post-PythonBook"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Python啃书笔记</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-07-10 15:20:36" datetime="2020-07-10T07:20:36.000Z"  itemprop="datePublished">2020-07-10</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E7%BC%96%E7%A8%8B/">编程</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>[TOC]</p>
<h2 id="变量和简单数据类型"><a href="#变量和简单数据类型" class="headerlink" title="变量和简单数据类型"></a>变量和简单数据类型</h2><h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><h4 id="使用方法修改字符串的大小写"><a href="#使用方法修改字符串的大小写" class="headerlink" title="使用方法修改字符串的大小写"></a>使用方法修改字符串的大小写</h4><ul>
<li>title() 该方法实现了单词首字母大写输出，例如姓名之间有空格会被识别为两个单词</li>
<li>upper() 该方法实现了全部字母大写输出</li>
<li>lower() 该方法实现了全部字母小写输出</li>
</ul>
<h4 id="合并（拼接）字符串"><a href="#合并（拼接）字符串" class="headerlink" title="合并（拼接）字符串"></a>合并（拼接）字符串</h4><p>v1+“ ”+v2</p>
<p>如果字符串与整型变量拼接的话，会出现类型错误，可以使用str()函数将整型变量格式化为字符串，防止歧义发生</p>
<h4 id="使用制表符或换行符来添加空白"><a href="#使用制表符或换行符来添加空白" class="headerlink" title="使用制表符或换行符来添加空白"></a>使用制表符或换行符来添加空白</h4><ul>
<li>\t 添加一个制表符，VS2019编辑器中为四个空格，命令行为八个空格的第一位</li>
<li>\n 换行</li>
</ul>
<h4 id="删除空白"><a href="#删除空白" class="headerlink" title="删除空白"></a>删除空白</h4><p>以下是所使用的方法</p>
<ul>
<li>strip() 删除起始，不删中间</li>
<li>lstrip() 删除起始空白</li>
<li>rstrip() 删除尾部空白</li>
</ul>
<h3 id="数字"><a href="#数字" class="headerlink" title="数字"></a>数字</h3><h4 id="整数"><a href="#整数" class="headerlink" title="整数"></a>整数</h4><ul>
<li><p>可支持加减乘除运算以及高级运算次序，</p>
<p>相除运算会得出小数</p>
</li>
<li><p>两个星号表示乘方</p>
</li>
<li><p>空格不影响运算，只是为了方便阅读</p>
</li>
</ul>
<h4 id="浮点数"><a href="#浮点数" class="headerlink" title="浮点数"></a>浮点数</h4><p>浮点数是无限逼近，需要注意结果中包含小数位是不确定的</p>
<h4 id="使用函数str-避免类型错误"><a href="#使用函数str-避免类型错误" class="headerlink" title="使用函数str()避免类型错误"></a>使用函数str()避免类型错误</h4><ul>
<li><p>字符与整型变量相加时，Python不知道如何去解读，可以用str()函数包裹变量参与运算</p>
<p>即在处理非字符型与字符型变量运算时Python是否会按你所期望的方式解读</p>
</li>
<li><p>Python2中的除法运算类似于C语言，可以实现自动类型转换</p>
</li>
</ul>
<h4 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h4><p>记住一点，注释是给人看的</p>
<h4 id="Python之禅"><a href="#Python之禅" class="headerlink" title="Python之禅"></a>Python之禅</h4><p>在命令窗口输入import this回车，即可看到Python之禅</p>
<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><ul>
<li><p>字符串定义时含有斜撇的注意单双引号的嵌套</p>
</li>
<li><p>确认是否能够在运算中自动转换为高级数据类型，</p>
<p>​    整型乘浮点型得出浮点型</p>
<p>​    浮点型乘浮点型得出浮点型</p>
<p>​    实验也可以证明我的猜想</p>
</li>
</ul>
<h2 id="列表简介"><a href="#列表简介" class="headerlink" title="列表简介"></a>列表简介</h2><h3 id="列表是什么"><a href="#列表是什么" class="headerlink" title="列表是什么"></a>列表是什么</h3><ul>
<li><p>用方括号来表示 [ ] 单引号包裹元素，逗号分隔元素，属于<u>有序集合</u></p>
</li>
<li><p>可使用valuename=[ ] 创建一个空列表，方括号中的空格仅做美化用处，会被忽略掉</p>
</li>
<li><p>列表通常包含多个元素，请给予复数名称</p>
</li>
<li><p>打印输出列表变量名时，包括方括号</p>
</li>
</ul>
<h4 id="访问列表元素"><a href="#访问列表元素" class="headerlink" title="访问列表元素"></a>访问列表元素</h4><ul>
<li>有序集合，索引从零开始</li>
<li>可存在相同元素</li>
<li>可与对象.方法结合，实现格式化输出</li>
<li>使用valuename[-1]访问倒数第一个元素，以此类推</li>
</ul>
<h3 id="修改、添加和删除元素"><a href="#修改、添加和删除元素" class="headerlink" title="修改、添加和删除元素"></a>修改、添加和删除元素</h3><h4 id="修改列表元素"><a href="#修改列表元素" class="headerlink" title="修改列表元素"></a>修改列表元素</h4><p>valuename[n]选中元素即可对其重新赋值</p>
<h4 id="在列表中添加元素"><a href="#在列表中添加元素" class="headerlink" title="在列表中添加元素"></a>在列表中添加元素</h4><ul>
<li>使用append()方法将元素追加到列表尾部<ul>
<li>append(‘element’)</li>
</ul>
</li>
<li>使用insert(number,’element’)方法插入到列表中<ul>
<li>该方法需要提供插入位置，和插入元素</li>
</ul>
</li>
</ul>
<h4 id="从列表中删除元素"><a href="#从列表中删除元素" class="headerlink" title="从列表中删除元素"></a>从列表中删除元素</h4><ul>
<li>使用del语句删除元素<ul>
<li>del valuename[n] 来删除各个位置的元素，永久性删除</li>
</ul>
</li>
<li>使用pop()方法来删除元素<ul>
<li>直接使用为弹出末端元素，被弹出的元素不再在列表中</li>
<li>传入索引参数可以删除指定元素</li>
<li>pop()方法删除后该元素仍可使用，具体不清楚，暂时性删除</li>
</ul>
</li>
<li>使用remove()方法，根据元素的值删除元素<ul>
<li>只会删除第一个遇到的值，如需删除多个，请结合循环</li>
<li>也验证了可以存在相同值的元素</li>
</ul>
</li>
</ul>
<h3 id="组织列表"><a href="#组织列表" class="headerlink" title="组织列表"></a>组织列表</h3><p>列表中的元素顺序无法预测，有时候需要保留最初，时候需要重新排序，Python提供了很多组织列表的方式，可根据具体情况选用。</p>
<h4 id="使用sort-方法对列表进行永久性排序"><a href="#使用sort-方法对列表进行永久性排序" class="headerlink" title="使用sort()方法对列表进行永久性排序"></a>使用sort()方法对列表进行<u>永久性</u>排序</h4><ul>
<li>对象.方法，这句建议独立出来写</li>
<li>按首字母abc的顺序排列</li>
<li>向sort()传递参数reverse=Ture可实现倒序永久性排序</li>
</ul>
<h4 id="使用sorted-函数对列表进行临时排序"><a href="#使用sorted-函数对列表进行临时排序" class="headerlink" title="使用sorted()函数对列表进行临时排序"></a>使用sorted()函数对列表进行临时排序</h4><p>print(sorted(valuename))可实现临时按字母顺序abc升序排列</p>
<p>也可向sorted()传递参数reverse=Ture实现临时倒序排列，使用方法暂未查询</p>
<h4 id="倒着打印列表"><a href="#倒着打印列表" class="headerlink" title="倒着打印列表"></a>倒着打印列表</h4><ul>
<li>使用reverse()方法，valuename.reverse()，建议这句单独写</li>
<li>不是按照字母相反顺序实现倒序输出，而是按照元素的排列顺序倒着来</li>
<li>是永久性的，但是可以二次使用再实现正序</li>
</ul>
<h5 id="确定列表的长度"><a href="#确定列表的长度" class="headerlink" title="确定列表的长度"></a>确定列表的长度</h5><p>使用len()函数可获取列表长度，从1开始</p>
<h2 id="操作列表"><a href="#操作列表" class="headerlink" title="操作列表"></a>操作列表</h2><p><u>考虑软硬概念，软删除，硬删除</u></p>
<h3 id="遍历整个列表"><a href="#遍历整个列表" class="headerlink" title="遍历整个列表"></a>遍历整个列表</h3><h4 id="深入研究循环"><a href="#深入研究循环" class="headerlink" title="深入研究循环"></a>深入研究循环</h4><p>for循环</p>
<p>不需要判断条件，摆脱C语言猜想，直接 dog in dogs，cat in cats </p>
<h4 id="避免出现缩进问题，不可遗漏冒号"><a href="#避免出现缩进问题，不可遗漏冒号" class="headerlink" title="避免出现缩进问题，不可遗漏冒号"></a>避免出现缩进问题，不可遗漏冒号</h4><h3 id="创建数值列表"><a href="#创建数值列表" class="headerlink" title="创建数值列表"></a>创建数值列表</h3><p>使用range()函数生成一系列数字，可以给定整数范围像range(1,5)</p>
<p>​    这样就会产生1,2,3,4,四个整数！记住这个易错点</p>
<h4 id="使用list-创建数字列表"><a href="#使用list-创建数字列表" class="headerlink" title="使用list()创建数字列表"></a>使用list()创建数字列表</h4><p>让range()做list的参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">numbers = list(range(<span class="number">1</span>, <span class="number">6</span>))</span><br><span class="line">print(numbers)</span><br><span class="line"><span class="comment"># [1, 2, 3, 4, 5]</span></span><br></pre></td></tr></table></figure>

<p>可以使用append()函数来创建列表</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">squares = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, <span class="number">6</span>):</span><br><span class="line">    <span class="comment"># value = i ** 2</span></span><br><span class="line">    squares.append(i**<span class="number">2</span>)<span class="comment"># 这是一个语句</span></span><br><span class="line">print(squares)</span><br><span class="line"><span class="comment"># [1, 4, 9, 16, 25]</span></span><br></pre></td></tr></table></figure>

<h4 id="对数字列表执行简单的统计计算"><a href="#对数字列表执行简单的统计计算" class="headerlink" title="对数字列表执行简单的统计计算"></a>对数字列表执行简单的统计计算</h4><p>使用函数 min() max() sum() 这几个常用函数要记住</p>
<h3 id="列表解析"><a href="#列表解析" class="headerlink" title="列表解析"></a>列表解析</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">squares = [value ** <span class="number">2</span> <span class="keyword">for</span> value <span class="keyword">in</span> range(<span class="number">1</span>, <span class="number">6</span>)]</span><br><span class="line">print(squares)</span><br><span class="line"><span class="comment"># 这玩意比较高级，练习几遍，看结构就能懂了</span></span><br></pre></td></tr></table></figure>

<h3 id="使用列表的一部分"><a href="#使用列表的一部分" class="headerlink" title="使用列表的一部分"></a>使用列表的一部分</h3><h4 id="切片"><a href="#切片" class="headerlink" title="切片"></a>切片</h4><p>切片的输出结果是一个列表</p>
<p>list[m:n] 这是一个切片，起始从0算起，输出时有头无尾巴巴</p>
<p>左边索引从0开始 右边从-1开始</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">players = [<span class="string">'sandy'</span>, <span class="string">'kura'</span>, <span class="string">'jaysi'</span>, <span class="string">'jhon'</span>, <span class="string">'tenway'</span>, <span class="string">'adame'</span>]</span><br><span class="line">print(str(players[<span class="number">0</span>:<span class="number">3</span>]).title())  <span class="comment"># 掐头去尾输出 ['Sandy', 'Kura', 'Jaysi']</span></span><br><span class="line"><span class="comment"># 左边省略写法</span></span><br><span class="line">print(str(players[:<span class="number">3</span>]).title())  <span class="comment"># 表示从开头输出到3之前的位置终止 ['Sandy', 'Kura', 'Jaysi']</span></span><br><span class="line"><span class="comment"># 右边省略写法</span></span><br><span class="line">print(str(players[<span class="number">1</span>:]).title())  <span class="comment"># 表示从1号位开始输出，直至列表结束 ['Kura', 'Jaysi', 'Jhon', 'Tenway', 'Adame']</span></span><br><span class="line"><span class="comment"># 右边省略写法</span></span><br><span class="line">print(str(players[<span class="number">-2</span>:]).title())  <span class="comment"># 表示从-2号位开始输出，直至列表结束 ['Tenway', 'Adame']</span></span><br><span class="line">print(str(players[:]).title())  <span class="comment"># 方括号内全省略，保留冒号 输出整个列表，['Sandy', 'Kura', 'Jaysi', 'Jhon', 'Tenway', 'Adame']</span></span><br></pre></td></tr></table></figure>

<h4 id="遍历切片"><a href="#遍历切片" class="headerlink" title="遍历切片"></a>遍历切片</h4><p>现在只啃到了for循环，可以使用切片来代替in 后面的位置</p>
<h4 id="复制列表"><a href="#复制列表" class="headerlink" title="复制列表"></a>复制列表</h4><p>可以使用切片实现指定部分复制，理解为取切片创建副本</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">humans = players[:]</span><br><span class="line">humans.append(<span class="string">'sasa'</span>)</span><br><span class="line">print(humans)<span class="comment"># 推荐使用切片创建副本复制的方法</span></span><br><span class="line"><span class="comment">#['sandy', 'kura', 'jaysi', 'jhon', 'tenway', 'adame', 'sasa']</span></span><br><span class="line">print(players)</span><br><span class="line"><span class="comment">#['sandy', 'kura', 'jaysi', 'jhon', 'tenway', 'adame']</span></span><br></pre></td></tr></table></figure>

<p>直接使用变量名复制，其意义不同，相当于把新列表指向了源列表</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 另一种是使用变量名进行复制，相当于把两个变量指向了同一个列表，对所谓的第二列表进行修改时，源列表也会随之改变。</span></span><br><span class="line">humans = players</span><br><span class="line">humans.append(<span class="string">'sasa'</span>)</span><br><span class="line">print(humans)<span class="comment">#['sandy', 'kura', 'jaysi', 'jhon', 'tenway', 'adame', 'sasa']</span></span><br><span class="line">print(players)<span class="comment">#['sandy', 'kura', 'jaysi', 'jhon', 'tenway', 'adame', 'sasa']</span></span><br></pre></td></tr></table></figure>

<h3 id="元组"><a href="#元组" class="headerlink" title="元组"></a>元组</h3><p>书上解释为不能修改的列表，用圆括号()来区分，可以使用索引，切片，遍历等进行访问</p>
<p>但是不能对其内的元素进行修改</p>
<p>但但是，可以将这个Tuple重新赋值，即开创新的Tuple（滑稽），可以当做二次初始化这个变量名所指</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">tea = (<span class="string">'wulong'</span>, <span class="string">'puer'</span>, <span class="string">'longjing'</span>, <span class="string">'biluochun'</span>)</span><br><span class="line">print(tea[:<span class="number">2</span>])  <span class="comment"># 可以使用切片，索引等列表操作，输出为元组</span></span><br><span class="line"><span class="comment">#二次初始化，修改元组变量</span></span><br><span class="line">tea = (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">print(tea[:<span class="number">2</span>])  <span class="comment"># (1, 2)</span></span><br></pre></td></tr></table></figure>

<h2 id="if语句"><a href="#if语句" class="headerlink" title="if语句"></a>if语句</h2><h4 id="条件测试"><a href="#条件测试" class="headerlink" title="条件测试"></a>条件测试</h4><p>根据表达式的布尔值来确定是否进入分支</p>
<h3 id="if-else语句"><a href="#if-else语句" class="headerlink" title="if-else语句"></a>if-else语句</h3><p>两条分支的语句</p>
<h3 id="if-elif-else"><a href="#if-elif-else" class="headerlink" title="if-elif-else"></a>if-elif-else</h3><p>这是个神奇的语句，在于并不是每个if都有else对应</p>
<h4 id="多个elif，与else的省略"><a href="#多个elif，与else的省略" class="headerlink" title="多个elif，与else的省略"></a>多个elif，与else的省略</h4><p>哒哒哒很好理解，我选择综合一下，敲一个剪刀石头布的案例</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 会用到随机数模块random()</span></span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取用户猜拳选项</span></span><br><span class="line">player = input(<span class="string">"请输入你的猜拳选项，直接输入中文即可"</span>)</span><br><span class="line"><span class="comment"># print(player)</span></span><br><span class="line"><span class="keyword">if</span> player == <span class="string">'剪刀'</span>:</span><br><span class="line">    player = <span class="number">0</span></span><br><span class="line"><span class="keyword">if</span> player == <span class="string">'石头'</span>:</span><br><span class="line">    player = <span class="number">1</span></span><br><span class="line"><span class="keyword">if</span> player == <span class="string">'布'</span>:</span><br><span class="line">    player = <span class="number">2</span></span><br><span class="line"><span class="comment"># 生成机器猜拳选项</span></span><br><span class="line">computer = random.randint(<span class="number">0</span>, <span class="number">2</span>)</span><br><span class="line"><span class="comment"># 判断模块</span></span><br><span class="line"><span class="keyword">if</span> player == <span class="number">0</span> <span class="keyword">and</span> computer == <span class="number">2</span>:</span><br><span class="line">    print(<span class="string">'机器猜的是布'</span>)</span><br><span class="line">    print(<span class="string">'所以，本局你赢了'</span>)</span><br><span class="line"><span class="keyword">elif</span> player == <span class="number">1</span> <span class="keyword">and</span> computer == <span class="number">0</span>:</span><br><span class="line">    print(<span class="string">'机器猜的是剪刀'</span>)</span><br><span class="line">    print(<span class="string">'所以，本局你赢了'</span>)</span><br><span class="line"><span class="keyword">elif</span> player == <span class="number">2</span> <span class="keyword">and</span> computer == <span class="number">1</span>:</span><br><span class="line">    print(<span class="string">'机器猜的是石头'</span>)</span><br><span class="line">    print(<span class="string">'所以，本局你赢了'</span>)</span><br><span class="line"><span class="keyword">elif</span> player == computer:</span><br><span class="line">    print(<span class="string">"无论如何，菜批你输了！"</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    print(<span class="string">'两者相同，所以本局平局'</span>)</span><br><span class="line"><span class="comment"># 学到了这个elif最终只能跟一个else，并不能每一步的elif都跟一个</span></span><br></pre></td></tr></table></figure>

<h3 id="for-in设置两个可迭代对象"><a href="#for-in设置两个可迭代对象" class="headerlink" title="for-in设置两个可迭代对象"></a>for-in设置两个可迭代对象</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">name = [<span class="string">'sesa'</span>, <span class="string">'kora'</span>, <span class="string">'nekasa'</span>, <span class="string">'satana'</span>, <span class="string">'norii'</span>]</span><br><span class="line">man = [<span class="string">'sesa'</span>, <span class="string">'nekasa'</span>, <span class="string">'norii'</span>]</span><br><span class="line"><span class="keyword">for</span> nan <span class="keyword">in</span> man:</span><br><span class="line">    <span class="comment"># 设置这个nan用来便利存储man的数据</span></span><br><span class="line">    <span class="keyword">if</span> nan <span class="keyword">in</span> name:</span><br><span class="line">        <span class="comment"># 如果这个nan包含在name里边，就输出它</span></span><br><span class="line">        print(nan.title())</span><br><span class="line"><span class="comment"># 好像是我的错觉，并不是两个可迭代变量的循环</span></span><br></pre></td></tr></table></figure>

<h2 id="字典（dictionary）"><a href="#字典（dictionary）" class="headerlink" title="字典（dictionary）"></a>字典（dictionary）</h2><h3 id="一个简单的字典"><a href="#一个简单的字典" class="headerlink" title="一个简单的字典"></a>一个简单的字典</h3><p>可以理解为<em>键-值对</em>的模式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">alien_0 = &#123;<span class="string">'color'</span>: <span class="string">'green'</span>, <span class="string">'points'</span>: <span class="number">5</span>&#125;</span><br><span class="line"><span class="comment"># 这个外星人是绿色的，价值5点</span></span><br><span class="line">print(alien_0[<span class="string">'color'</span>])</span><br><span class="line">print(alien_0[<span class="string">'points'</span>])</span><br><span class="line"><span class="comment"># green</span></span><br><span class="line"><span class="comment"># 5</span></span><br></pre></td></tr></table></figure>

<p>记住定义的样式，以及输出时的方式</p>
<h3 id="使用字典"><a href="#使用字典" class="headerlink" title="使用字典"></a>使用字典</h3><p>字典的访问，就像列表切片的写法valuename[‘key’]</p>
<p><strong>另外特别强调没有顺序可言</strong></p>
<h4 id="添加键-值对"><a href="#添加键-值对" class="headerlink" title="添加键-值对"></a>添加键-值对</h4><p>字典是一种动态结构，可随时在其中添加键-值对。要添加键值对，可依次指定字典名、用方括号括起来的键和相关联的值。</p>
<p>注意，<u>键-值对的排列顺序与添加顺序不同</u>。Python不关心键-值对的添加顺序，而只关心键和值之间的关联关系。</p>
<p>创建一个空字典，dictionary = { }，然后可以以此为其添加键-值对</p>
<h4 id="修改字典中的值"><a href="#修改字典中的值" class="headerlink" title="修改字典中的值"></a>修改字典中的值</h4><p>先选中后修改</p>
<p>使用dict-name[key]=new value，可以将原来的键所对应的值覆盖掉</p>
<h4 id="删除键-值对"><a href="#删除键-值对" class="headerlink" title="删除键-值对"></a>删除键-值对</h4><p>可以使用del 语句来删除</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">alien = &#123;<span class="string">'color'</span>: <span class="string">'yellow'</span>, <span class="string">'points'</span>: <span class="number">5</span>&#125;</span><br><span class="line">print(alien)</span><br><span class="line"><span class="keyword">del</span> alien[<span class="string">'points'</span>]</span><br><span class="line">print(alien)</span><br><span class="line"><span class="comment"># &#123;'color': 'yellow', 'points': 5&#125;</span></span><br><span class="line"><span class="comment"># &#123;'color': 'yellow'&#125;</span></span><br></pre></td></tr></table></figure>

<p>这将是硬删除，即永远删除</p>
<h4 id="由类似对象组成的字典"><a href="#由类似对象组成的字典" class="headerlink" title="由类似对象组成的字典"></a>由类似对象组成的字典</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">favorite_languages = &#123;</span><br><span class="line">    <span class="string">'jen'</span>: <span class="string">'python'</span>,  <span class="comment"># 我终于理解了这个逗号在JavaScript中的含义！</span></span><br><span class="line">    <span class="string">'sarah'</span>: <span class="string">'c'</span>,</span><br><span class="line">    <span class="string">'neraii'</span>: <span class="string">'c#'</span>,</span><br><span class="line">    <span class="string">'korasa'</span>: <span class="string">'go'</span></span><br><span class="line">&#125;</span><br><span class="line">print(<span class="string">"Neraii's favorite language is "</span> + favorite_languages[<span class="string">'neraii'</span>].title() + <span class="string">"."</span>)</span><br><span class="line"><span class="comment"># Neraii's favorite language is C#.</span></span><br></pre></td></tr></table></figure>

<h3 id="遍历字典"><a href="#遍历字典" class="headerlink" title="遍历字典"></a>遍历字典</h3><h4 id="for循环遍历字典的方式"><a href="#for循环遍历字典的方式" class="headerlink" title="for循环遍历字典的方式"></a>for循环遍历字典的方式</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">items = &#123;</span><br><span class="line">    <span class="string">'name'</span>: <span class="string">'naraii'</span>,</span><br><span class="line">    <span class="string">'age'</span>: <span class="number">18</span>,</span><br><span class="line">    <span class="string">'tall'</span>: <span class="number">175</span>,</span><br><span class="line">    <span class="string">'birthday'</span>: <span class="string">'3月21日'</span>,</span><br><span class="line">    <span class="string">'favorite_language'</span>: <span class="string">'python'</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># 下面的key和value是泛指，如果是人名和语言的话用name，language更好</span></span><br><span class="line"><span class="keyword">for</span> key, value <span class="keyword">in</span> items.items():</span><br><span class="line">    print(<span class="string">'Key: &#123;&#125;\nValue: &#123;&#125;\n'</span>.format(key, str(value).title()))</span><br><span class="line"><span class="comment"># 重点竟然在于这个items()方法,另外.title()竟然可以识别下划线_</span></span><br><span class="line"><span class="comment"># Key: name</span></span><br><span class="line"><span class="comment"># Value: Naraii</span></span><br><span class="line"><span class="comment"># Key: age</span></span><br><span class="line"><span class="comment"># Value: 18</span></span><br><span class="line"><span class="comment"># Key: tall</span></span><br><span class="line"><span class="comment"># Value: 175</span></span><br><span class="line"><span class="comment"># Key: birthday</span></span><br><span class="line"><span class="comment"># Value: 3月21日</span></span><br><span class="line"><span class="comment"># Key: favorite_language</span></span><br><span class="line"><span class="comment"># Value: Python</span></span><br><span class="line">print(items.items())</span><br><span class="line"><span class="comment"># dict_items([('name', 'naraii'), ('age', 18), ('tall', 175), ('birthday', '3月21日'), ('favorite_language', 'python')])</span></span><br><span class="line"><span class="comment"># 奇怪的一批的返回值，类型是dict_items</span></span><br></pre></td></tr></table></figure>

<p>此处学会一个新的方法 items() 返回可遍历的(键, 值) <u>元组</u><em>数组</em>，会应用于遍历就行了</p>
<h4 id="遍历字典中的键"><a href="#遍历字典中的键" class="headerlink" title="遍历字典中的键"></a>遍历字典中的键</h4><p>默认就是遍历所有的键，但是我们推荐使用方法keys()</p>
<p>该方法的返回值是一个列表，</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">items = &#123;</span><br><span class="line">    <span class="string">'name'</span>: <span class="string">'naraii'</span>,</span><br><span class="line">    <span class="string">'age'</span>: <span class="number">18</span>,</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># 主要学会使用 keys() 方法</span></span><br><span class="line"><span class="keyword">for</span> key <span class="keyword">in</span> items.keys():</span><br><span class="line">    print(<span class="string">'Key: &#123;&#125;'</span>.format(key))</span><br><span class="line"><span class="comment"># Key: name</span></span><br><span class="line"><span class="comment"># Key: age</span></span><br></pre></td></tr></table></figure>

<h4 id="按顺序遍历字典中所有的键"><a href="#按顺序遍历字典中所有的键" class="headerlink" title="按顺序遍历字典中所有的键"></a>按顺序遍历字典中所有的键</h4><p>使用到组织列表时学到的sorted()函数,进行临时排序，该返回值是一个新列表，该列表按升序包含项目中可迭代的所有项。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">items = &#123;</span><br><span class="line">    <span class="string">'name'</span>: <span class="string">'naraii'</span>,</span><br><span class="line">    <span class="string">'age'</span>: <span class="number">18</span>,</span><br><span class="line">&#125;</span><br><span class="line">print(sorted(items.keys()))</span><br><span class="line"><span class="comment"># 返回值是 ['age', 'name']</span></span><br><span class="line">print(items.keys())</span><br><span class="line"><span class="comment"># 再输出还是未变 dict_keys(['name', 'age'])</span></span><br></pre></td></tr></table></figure>

<h4 id="遍历字典中所有的值"><a href="#遍历字典中所有的值" class="headerlink" title="遍历字典中所有的值"></a>遍历字典中所有的值</h4><p>主要使用values() 方法，返回值为列表，不包含任何键</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 主要使用 values() 方法</span></span><br><span class="line">favorite_languages = &#123;</span><br><span class="line">    <span class="string">'naraii'</span>:<span class="string">'python'</span>,</span><br><span class="line">    <span class="string">'sanote'</span>:<span class="string">'java'</span>,</span><br><span class="line">    <span class="string">'wily'</span>:<span class="string">'c++'</span>,</span><br><span class="line">    <span class="string">'zara'</span>:<span class="string">'python'</span>,</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> v <span class="keyword">in</span> favorite_languages.values():</span><br><span class="line">    print(<span class="string">"Value: &#123;&#125;"</span>.format(v.title()))</span><br><span class="line"><span class="comment"># Value: Python</span></span><br><span class="line"><span class="comment"># Value: Java</span></span><br><span class="line"><span class="comment"># Value: C++</span></span><br><span class="line"><span class="comment"># Value: Python</span></span><br></pre></td></tr></table></figure>

<p>针对重复元素，可以利用集合来处理，因为集合中的元素要求独一无二，我们可以利用返回值来建立一个集合，针对for循环后边的可迭代变量使用set()函数处理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">favorite_languages = &#123;</span><br><span class="line">    <span class="string">'naraii'</span>:<span class="string">'python'</span>,</span><br><span class="line">    <span class="string">'sanote'</span>:<span class="string">'java'</span>,</span><br><span class="line">    <span class="string">'wily'</span>:<span class="string">'c++'</span>,</span><br><span class="line">    <span class="string">'zara'</span>:<span class="string">'python'</span>,</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> v <span class="keyword">in</span> set(favorite_languages.values()):</span><br><span class="line">    print(<span class="string">"Value: &#123;&#125;"</span>.format(v.title()))</span><br><span class="line"><span class="comment"># Value: Java</span></span><br><span class="line"><span class="comment"># Value: Python</span></span><br><span class="line"><span class="comment"># Value: C++</span></span><br></pre></td></tr></table></figure>

<h3 id="嵌套"><a href="#嵌套" class="headerlink" title="嵌套"></a>嵌套</h3><p>猜测涉及到深考本和浅拷贝</p>
<h4 id="字典列表"><a href="#字典列表" class="headerlink" title="字典列表"></a>字典列表</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">aline_0 = &#123;</span><br><span class="line">    <span class="string">'color'</span>: <span class="string">'green'</span>,</span><br><span class="line">    <span class="string">'points'</span>: <span class="number">5</span></span><br><span class="line">&#125;</span><br><span class="line">aline_1 = &#123;</span><br><span class="line">    <span class="string">'color'</span>: <span class="string">'yellow'</span>,</span><br><span class="line">    <span class="string">'points'</span>: <span class="number">10</span></span><br><span class="line">&#125;</span><br><span class="line">aline_2 = &#123;</span><br><span class="line">    <span class="string">'color'</span>: <span class="string">'red'</span>,</span><br><span class="line">    <span class="string">'points'</span>: <span class="number">15</span></span><br><span class="line">&#125;</span><br><span class="line">alines = [aline_0, aline_1, aline_2]</span><br><span class="line"><span class="keyword">for</span> aline <span class="keyword">in</span> alines:</span><br><span class="line">    print(aline)</span><br><span class="line"><span class="comment"># 输出结果是一个带花括号的字典</span></span><br></pre></td></tr></table></figure>

<h4 id="字典中存储列表"><a href="#字典中存储列表" class="headerlink" title="字典中存储列表"></a>字典中存储列表</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">alines = []</span><br><span class="line"><span class="keyword">for</span> aline_number <span class="keyword">in</span> range(<span class="number">5</span>):</span><br><span class="line">    new_aline = &#123;</span><br><span class="line">        <span class="string">'color'</span>: <span class="string">'yellow'</span>,</span><br><span class="line">        <span class="string">'points'</span>: <span class="number">10</span></span><br><span class="line">    &#125;</span><br><span class="line">    alines.append(new_aline)</span><br><span class="line">print(alines)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 显示前三个外星人</span></span><br><span class="line"><span class="keyword">for</span> aline <span class="keyword">in</span> alines[:<span class="number">3</span>]:</span><br><span class="line">    print(aline)</span><br><span class="line">print(<span class="string">'...'</span>)</span><br><span class="line">print(<span class="string">'一共创建了&#123;&#125;个外星人'</span>.format(str(len(alines))))</span><br><span class="line"><span class="comment"># 由此可见，len在此处获得的是元素个数</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 对前两个元素内容进行修改</span></span><br><span class="line"><span class="keyword">for</span> aline <span class="keyword">in</span> alines[:<span class="number">2</span>]:</span><br><span class="line">    <span class="keyword">if</span> aline[<span class="string">'color'</span>] == <span class="string">'yellow'</span>:  <span class="comment"># 注意这里是等等于</span></span><br><span class="line">        aline[<span class="string">'color'</span>] = <span class="string">'green'</span></span><br><span class="line">        aline[<span class="string">'points'</span>] = <span class="number">15</span></span><br><span class="line">print(alines)  <span class="comment"># 注意alines是一个列表，嵌套了字典</span></span><br><span class="line"><span class="comment"># [&#123;'color': 'green', 'points': 15&#125;, &#123;'color': 'green', 'points': 15&#125;, &#123;'color': 'yellow', 'points': 10&#125;, &#123;'color': 'yellow', 'points': 10&#125;, &#123;'color': 'yellow', 'points': 10&#125;]</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 下面是我尝试使用另一种写法来实现修改后面的点数与颜色</span></span><br><span class="line"><span class="keyword">for</span> aline <span class="keyword">in</span> alines[<span class="number">3</span>:]:</span><br><span class="line">    <span class="keyword">for</span> value <span class="keyword">in</span> aline.values():</span><br><span class="line">        <span class="comment"># 这里需要关注，values()方法的返回值是一个元组，我没也并没有直接对不可变类型的元组进行修改，而是继续遍历它，对原alines数据进行修改</span></span><br><span class="line">        <span class="keyword">if</span> value == <span class="string">'yellow'</span>:</span><br><span class="line">            aline[<span class="string">'color'</span>] = <span class="string">'red'</span></span><br><span class="line">            aline[<span class="string">'points'</span>] = <span class="number">20</span></span><br><span class="line">print(alines)</span><br><span class="line"><span class="comment"># [&#123;'color': 'green', 'points': 15&#125;, &#123;'color': 'green', 'points': 15&#125;, &#123;'color': 'yellow', 'points': 10&#125;, &#123;'color': 'red', 'points': 20&#125;, &#123;'color': 'red', 'points': 20&#125;]</span></span><br></pre></td></tr></table></figure>

<h4 id="字典中存储字典"><a href="#字典中存储字典" class="headerlink" title="字典中存储字典"></a>字典中存储字典</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 字典拥有无序性，根据其产生的结果同样具有无序性</span></span><br><span class="line">favorite_languages = &#123;</span><br><span class="line">    <span class="string">'jen'</span>: [<span class="string">'python'</span>, <span class="string">'java'</span>],</span><br><span class="line">    <span class="string">'naraii'</span>: [<span class="string">'c'</span>, <span class="string">'python'</span>],</span><br><span class="line">    <span class="string">'sarah'</span>: [<span class="string">'go'</span>, <span class="string">'ruby'</span>],</span><br><span class="line">    <span class="string">'phil'</span>: [<span class="string">'haskell'</span>, <span class="string">'python'</span>],</span><br><span class="line">    <span class="string">'sake'</span>: [<span class="string">'c#'</span>]</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">#  这个for循环竟然有两个变量参与，推测该方式仅常用于字典键-值对的遍历，并且使用可以返回与其相对应的值得方法</span></span><br><span class="line"><span class="keyword">for</span> name, languages <span class="keyword">in</span> favorite_languages.items():</span><br><span class="line">    <span class="comment"># 先复习下items() 方法的返回值类型&lt;class 'dict_items'&gt;可以将字典中的所有项，</span></span><br><span class="line">    <span class="comment"># 以列表方式返回，字典的每项作为列表的每对元素对</span></span><br><span class="line">    <span class="comment"># dict_items([('jen', ['python', 'java']), ('naraii', ['c', 'python']), ('sarah', ['go', 'ruby']), ('phil', ['haskell', 'python']),('sake',['c#']))])</span></span><br><span class="line">    <span class="keyword">if</span> len(languages) == <span class="number">1</span>:</span><br><span class="line">        print(<span class="string">'\n'</span> + name.title() + <span class="string">"'s favorite language is:"</span>)</span><br><span class="line">        <span class="keyword">for</span> language <span class="keyword">in</span> languages:  <span class="comment"># 这个并不能省掉，目的是重新迭代language</span></span><br><span class="line">            print(<span class="string">'\t'</span> + language.title())</span><br><span class="line">    <span class="keyword">else</span>:  <span class="comment"># 防止重复打印sake</span></span><br><span class="line">        print(<span class="string">'\n'</span> + name.title() + <span class="string">"'s favorite languages are:"</span>)</span><br><span class="line">        <span class="keyword">for</span> language <span class="keyword">in</span> languages:</span><br><span class="line">            print(<span class="string">'\t'</span> + language.title())</span><br><span class="line"><span class="comment"># Jen's favorite languages are:</span></span><br><span class="line"><span class="comment">#  Python</span></span><br><span class="line"><span class="comment">#  Java</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Naraii's favorite languages are:</span></span><br><span class="line"><span class="comment">#  C</span></span><br><span class="line"><span class="comment">#  Python</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Sarah's favorite languages are:</span></span><br><span class="line"><span class="comment">#  Go</span></span><br><span class="line"><span class="comment">#  Ruby</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Phil's favorite languages are:</span></span><br><span class="line"><span class="comment">#  Haskell</span></span><br><span class="line"><span class="comment">#  Python</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Sake's favorite language is:</span></span><br><span class="line"><span class="comment">#  C#</span></span><br></pre></td></tr></table></figure>

<h2 id="用户输入和while循环"><a href="#用户输入和while循环" class="headerlink" title="用户输入和while循环"></a>用户输入和while循环</h2><h3 id="函数-input-工作原理"><a href="#函数-input-工作原理" class="headerlink" title="函数 input() 工作原理"></a>函数 input() 工作原理</h3><h3 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h3><p>接受一个参数，向用户显示的提示或说明</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">prompt = <span class="string">'\nTell me something,and I will repeat it back to you:'</span></span><br><span class="line">prompt += <span class="string">"\nEnter 'quit' to end the program"</span></span><br><span class="line">message = <span class="string">""</span></span><br><span class="line"><span class="keyword">while</span> message != <span class="string">'quit'</span>:</span><br><span class="line">    message = input(prompt)</span><br><span class="line">    <span class="keyword">if</span> message != <span class="string">'quit'</span>:</span><br><span class="line">        print(message)</span><br><span class="line">        <span class="comment"># 当退出时不在显示 quit 字符串</span></span><br></pre></td></tr></table></figure>

<h3 id="类型转换"><a href="#类型转换" class="headerlink" title="类型转换"></a>类型转换</h3><p>需要获取非字符串型数据时需要进行类型转换，因为 input() 函数获取的都是字符串类型</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vlaue = int(input(<span class="string">'输入年龄'</span>))</span><br></pre></td></tr></table></figure>

<h3 id="求模运算符"><a href="#求模运算符" class="headerlink" title="求模运算符"></a>求模运算符</h3><p>% 取得运算结果的余数</p>
<ul>
<li><p>简单理解就是的出来的结果如果不是整数, 就取比结果小的最大整数</p>
</li>
<li><p>在Python中，取余的计算公式与别的语言并没有什么区别：</p>
<p>先取个整除，相积与份数，最后的出差</p>
<p>​    <strong>余 = 被 - 除 * [ 被 / / 除 ]</strong></p>
<p>会向下取整，试着去解释令人摸不着头脑的结果</p>
</li>
</ul>
<h3 id="使用标志"><a href="#使用标志" class="headerlink" title="使用标志"></a>使用标志</h3><p>相当于在千峰课程中老师讲到的”假设成立”法,下面我来展示一段</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">prompt = <span class="string">"\n 输入quit 即可退出："</span></span><br><span class="line">active = <span class="literal">True</span></span><br><span class="line"><span class="comment"># 建立假设</span></span><br><span class="line"><span class="keyword">while</span> active:</span><br><span class="line">    message = input(prompt)</span><br><span class="line">    <span class="keyword">if</span> message == <span class="string">'quit'</span>:</span><br><span class="line">        active = <span class="literal">False</span></span><br><span class="line">    <span class="comment">#     假设推翻</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        print(message)</span><br></pre></td></tr></table></figure>

<h3 id="break与continue的使用"><a href="#break与continue的使用" class="headerlink" title="break与continue的使用"></a>break与continue的使用</h3><p>使用思路与C语言相同，</p>
<ul>
<li>break结束本层循环</li>
<li>continue结束本次循环</li>
</ul>
<h3 id="使用while循环来处理列表和字典"><a href="#使用while循环来处理列表和字典" class="headerlink" title="使用while循环来处理列表和字典"></a>使用while循环来处理列表和字典</h3><h4 id="在列表之间移动元素"><a href="#在列表之间移动元素" class="headerlink" title="在列表之间移动元素"></a>在列表之间移动元素</h4><p>验证与未验证的用户</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 首先创建一个待验证用户列表confirm,vt,证实</span></span><br><span class="line"><span class="comment"># 和一个用于存储已验证用户的列表</span></span><br><span class="line">unconfirmed_users = [<span class="string">'alice'</span>, <span class="string">'eric'</span>, <span class="string">'john'</span>]</span><br><span class="line">confirmed_users = []</span><br><span class="line"><span class="comment"># 验证每个用户，直到没有待验证用户为止</span></span><br><span class="line"><span class="comment"># 将每个经过验证的用户转移到已验证用户的列表</span></span><br><span class="line"><span class="keyword">while</span> unconfirmed_users:</span><br><span class="line">    current_user = unconfirmed_users.pop()  <span class="comment"># 软删除 current,adj,现在的</span></span><br><span class="line">    print(<span class="string">'Verifying user: '</span> + current_user.title())</span><br><span class="line">    confirmed_users.append(current_user)  <span class="comment"># 将元素添加到新的列表</span></span><br><span class="line"><span class="comment"># 显示所有已验证的用户</span></span><br><span class="line">print(<span class="string">"\n The following users have been confirmed:"</span>)</span><br><span class="line"><span class="keyword">for</span> confirmed_user <span class="keyword">in</span> confirmed_users:</span><br><span class="line">    print(confirmed_user.title())</span><br></pre></td></tr></table></figure>

<h4 id="结合remove-方法删除重复元素"><a href="#结合remove-方法删除重复元素" class="headerlink" title="结合remove()方法删除重复元素"></a>结合remove()方法删除重复元素</h4><p>barabara，因为remove只会删除遇到的第一个元素，所以结合循环就可以删除后面的元素啦</p>
<h4 id="使用用户输入来填充字典"><a href="#使用用户输入来填充字典" class="headerlink" title="使用用户输入来填充字典"></a>使用用户输入来填充字典</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">responses = &#123;&#125;  <span class="comment"># response,n,响应，回答</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 建立一个标志，指出调查是否继续,polling,n,投票</span></span><br><span class="line">polling_active = <span class="literal">True</span></span><br><span class="line"><span class="keyword">while</span> polling_active:</span><br><span class="line">    <span class="comment"># 提示输入被调查者的名字和回答</span></span><br><span class="line">    name = input(<span class="string">"What's your name? "</span>)</span><br><span class="line">    response = input(<span class="string">"Which mountain would you like to climb someday? "</span>)</span><br><span class="line">    responses[name] = response</span><br><span class="line">    repeat = input(<span class="string">"Would you like to let another person respond?"</span>)</span><br><span class="line">    <span class="keyword">if</span> repeat == <span class="string">'no'</span>:</span><br><span class="line">        polling_active = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 调查结束，显示结果</span></span><br><span class="line">print(<span class="string">"\n--- Poll Results ---"</span>)</span><br><span class="line"><span class="keyword">for</span> name, response <span class="keyword">in</span> responses.items():</span><br><span class="line">    print(name + <span class="string">" would like to climb "</span> + response + <span class="string">'.'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h2><h3 id="定义函数"><a href="#定义函数" class="headerlink" title="定义函数"></a>定义函数</h3><p>大致可以看明白函数的基本结构了，</p>
<ul>
<li>由 def 定义，</li>
<li>后跟有带有圆括号的函数名，</li>
<li>然后是冒号，</li>
<li>下面是强制缩进的函数体</li>
<li>通过函数名加圆括号调用</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">greet_user</span><span class="params">()</span>:</span></span><br><span class="line">    print(<span class="string">"Hello"</span>)</span><br><span class="line">greet_user()</span><br></pre></td></tr></table></figure>

<h4 id="向函数传递信息"><a href="#向函数传递信息" class="headerlink" title="向函数传递信息"></a>向函数传递信息</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">greet_user</span><span class="params">(username)</span>:</span></span><br><span class="line">    print(<span class="string">"Hello"</span>, username)</span><br><span class="line"><span class="comment"># 调用时不能忽略参数，否则会报错</span></span><br><span class="line">greet_user(<span class="string">'Jack'</span>)</span><br></pre></td></tr></table></figure>

<h4 id="实参和形参"><a href="#实参和形参" class="headerlink" title="实参和形参"></a>实参和形参</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">greet_user</span><span class="params">(username)</span>:</span></span><br><span class="line">    print(<span class="string">"Hello"</span>, username)</span><br><span class="line">    <span class="comment"># 调用时需要传入必须的参数</span></span><br><span class="line">greet_user(<span class="string">'Jack'</span>)</span><br><span class="line"><span class="comment"># usernaem为形参，Jack为实参</span></span><br></pre></td></tr></table></figure>

<h3 id="传递实参"><a href="#传递实参" class="headerlink" title="传递实参"></a>传递实参</h3><h4 id="位置实参-大概就是尽量使用基于实参位置对应的形参"><a href="#位置实参-大概就是尽量使用基于实参位置对应的形参" class="headerlink" title="位置实参(大概就是尽量使用基于实参位置对应的形参)"></a>位置实参(大概就是尽量使用基于实参位置对应的形参)</h4><p>这要求实际参数的顺序与形式参数的顺序相同；也可使用关键字实参其中每个实参都由变量名和值组成；还可以使用字典列表bararaba</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">describe_pet</span><span class="params">(animal_type, pet_name)</span>:</span></span><br><span class="line">    <span class="string">"""显示宠物的信息"""</span></span><br><span class="line">    print(<span class="string">"\n我有一个"</span> + animal_type + <span class="string">'。'</span>)</span><br><span class="line">    print(<span class="string">"我的&#123;0&#125;的名字是&#123;1&#125;。"</span>.format(animal_type, pet_name))</span><br><span class="line">    <span class="comment"># 不能用含变量名的替换字段？，含数字或者空的都行</span></span><br><span class="line">describe_pet(<span class="string">'dog'</span>, <span class="string">'DDOG'</span>)</span><br><span class="line">describe_pet(<span class="string">'bage'</span>, <span class="string">'bird'</span>)</span><br><span class="line"><span class="comment"># 我有一个dog。</span></span><br><span class="line"><span class="comment"># 我的dog的名字是DDOG。</span></span><br><span class="line"><span class="comment"># 我有一个bage。</span></span><br><span class="line"><span class="comment"># 我的bage的名字是bird。</span></span><br></pre></td></tr></table></figure>

<h4 id="关键字实参"><a href="#关键字实参" class="headerlink" title="关键字实参"></a>关键字实参</h4><p>书上写的极好，我选择抄下来</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">关键字（并不系统的关键字）实参（看起来像关键字的参数名）是传递给函数的名称-值对，</span></span><br><span class="line"><span class="string">你直接在实参中将名称和值关联起来了，因此向函数传递实参时不会混淆。</span></span><br><span class="line"><span class="string">关键字实参让你无需考虑函数调用中的实参顺序，还清楚地指出了函数调用中各个值的用途。</span></span><br><span class="line"><span class="string">另外可以显式传值，就像print(end='barabara')这样来手动指定</span></span><br><span class="line"><span class="string">'''</span></span><br></pre></td></tr></table></figure>

<h4 id="默认值-指的是形参没给值，就用这个默认值"><a href="#默认值-指的是形参没给值，就用这个默认值" class="headerlink" title="默认值(指的是形参没给值，就用这个默认值)"></a>默认值(指的是形参没给值，就用这个默认值)</h4><p>设置方法是在定义时，对形参进行赋值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pet</span><span class="params">(petName, petType=<span class="string">'dog'</span>)</span>:</span></span><br><span class="line">    print(<span class="string">"我的宠物是&#123;1&#125;，它的名字叫&#123;0&#125;"</span>.format(petName.title(), petType).title())</span><br><span class="line"><span class="comment"># 给定了类型的默认值，因为大多数人的宠物都是狗子</span></span><br><span class="line">pet(<span class="string">'sake'</span>)</span><br><span class="line"><span class="comment"># 我的宠物是Dog，它的名字叫Sake</span></span><br></pre></td></tr></table></figure>

<p>在形参列表中使用默认值时，必须先列出没有默认值的形参，在列出有默认值的实参</p>
<h4 id="等效的函数调用"><a href="#等效的函数调用" class="headerlink" title="等效的函数调用"></a>等效的函数调用</h4><p>混合使用参数的传递方式（位置实参，关键字实参，默认值）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">pet(<span class="string">'harry'</span>, <span class="string">'hamster'</span>)  <span class="comment"># 显式！</span></span><br><span class="line">pet(petName=<span class="string">'harry'</span>, petType=<span class="string">'hamster'</span>)  <span class="comment"># 显式！</span></span><br><span class="line">pet(petType=<span class="string">'hamster'</span>, petName=<span class="string">'harry'</span>)  <span class="comment"># 颠倒！</span></span><br><span class="line"><span class="comment"># 我的宠物是Hamster，它的名字叫Harry</span></span><br><span class="line"><span class="comment"># 我的宠物是Hamster，它的名字叫Harry</span></span><br><span class="line"><span class="comment"># 我的宠物是Hamster，它的名字叫Harry</span></span><br></pre></td></tr></table></figure>

<h3 id="返回值"><a href="#返回值" class="headerlink" title="返回值"></a>返回值</h3><h4 id="返回简单值"><a href="#返回简单值" class="headerlink" title="返回简单值"></a>返回简单值</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_formatted_name</span><span class="params">(firstName, lastName)</span>:</span></span><br><span class="line">    <span class="comment"># 输入小写，返回标准的写法</span></span><br><span class="line">    fullName = firstName + <span class="string">" "</span> + lastName</span><br><span class="line">    <span class="keyword">return</span> fullName.title()</span><br><span class="line">musician = get_formatted_name(<span class="string">'jilimi'</span>, <span class="string">'hedax'</span>)</span><br><span class="line">print(musician)</span><br><span class="line"><span class="comment"># Jilimi Hedax</span></span><br></pre></td></tr></table></figure>

<h4 id="让实参变成可选的"><a href="#让实参变成可选的" class="headerlink" title="让实参变成可选的"></a>让实参变成可选的</h4><p>这样使用函数的人只需在必要时才提供额外的信息，使用默认值来实现此操作，但是要注意默认值形参只能放在参数表最后，传入实参时也放在最后（也可显式传入）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_formatted_name</span><span class="params">(firstName, lastName, middleName=<span class="string">''</span>)</span>:</span></span><br><span class="line">    <span class="comment"># 输入小写，返回标准的写法</span></span><br><span class="line">    fullName = firstName + <span class="string">" "</span> + middleName + <span class="string">" "</span> + lastName</span><br><span class="line">    <span class="keyword">return</span> fullName.title()</span><br><span class="line">musician = get_formatted_name(<span class="string">'jilimi'</span>, <span class="string">'hedax'</span>, <span class="string">'lee'</span>)</span><br><span class="line">print(musician)</span><br><span class="line"><span class="comment"># Jilimi Lee Hedax</span></span><br></pre></td></tr></table></figure>

<h4 id="返回字典"><a href="#返回字典" class="headerlink" title="返回字典"></a>返回字典</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">person_list</span><span class="params">(firstName, lastName, age=<span class="string">''</span>)</span>:</span></span><br><span class="line">    person = &#123;<span class="string">'姓'</span>: firstName, <span class="string">'名'</span>: lastName&#125;</span><br><span class="line">    <span class="keyword">if</span> age:</span><br><span class="line">        person[<span class="string">'age'</span>] = age</span><br><span class="line">    <span class="keyword">return</span> person</span><br><span class="line">print(person_list(<span class="string">'张'</span>, <span class="string">'三'</span>))</span><br><span class="line"><span class="comment"># &#123;'姓': '张', '名': '三'&#125;</span></span><br></pre></td></tr></table></figure>

<h4 id="结合使用函数和while循环"><a href="#结合使用函数和while循环" class="headerlink" title="结合使用函数和while循环"></a>结合使用函数和while循环</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">responses = &#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">survey_report</span><span class="params">(name, response)</span>:</span></span><br><span class="line">    responses[name] = response</span><br><span class="line"><span class="comment"># 这已经设计知识盲区了，竟然可以修改外部的值，竟然没有用return</span></span><br><span class="line"><span class="keyword">while</span> input(<span class="string">'是否继续'</span>) != <span class="string">'否'</span>:</span><br><span class="line">    name = input(<span class="string">"What's your name? "</span>)</span><br><span class="line">    response = input(<span class="string">"Which mountain would you like to climb someday? "</span>)</span><br><span class="line">    survey_report(name, response)</span><br><span class="line"><span class="comment"># 调查结束，显示结果</span></span><br><span class="line">print(<span class="string">"\n--- Poll Results ---"</span>)</span><br><span class="line"><span class="keyword">for</span> name, response <span class="keyword">in</span> responses.items():</span><br><span class="line">    print(name + <span class="string">" would like to climb "</span> + response + <span class="string">'.'</span>)</span><br><span class="line"><span class="comment"># 是否继续是</span></span><br><span class="line"><span class="comment"># What's your name? 王德发</span></span><br><span class="line"><span class="comment"># Which mountain would you like to climb someday? 泰山</span></span><br><span class="line"><span class="comment"># 是否继续是</span></span><br><span class="line"><span class="comment"># What's your name? 奈良子</span></span><br><span class="line"><span class="comment"># Which mountain would you like to climb someday? 富士山</span></span><br><span class="line"><span class="comment"># 是否继续否</span></span><br><span class="line"><span class="comment"># </span></span><br><span class="line"><span class="comment"># --- Poll Results ---</span></span><br><span class="line"><span class="comment"># 王德发 would like to climb 泰山.</span></span><br><span class="line"><span class="comment"># 奈良子 would like to climb 富士山.</span></span><br></pre></td></tr></table></figure>

<h3 id="传递列表"><a href="#传递列表" class="headerlink" title="传递列表"></a>传递列表</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">greet_user</span><span class="params">(names)</span>:</span></span><br><span class="line">    <span class="string">"""向列表中的用户致以简单的问候"""</span></span><br><span class="line">    <span class="keyword">for</span> name <span class="keyword">in</span> names:</span><br><span class="line">        <span class="comment"># 它采用循环的方式获得了每一个元素</span></span><br><span class="line">        msg = <span class="string">"Hello,&#123;&#125;!"</span>.format(name).title()</span><br><span class="line">        <span class="comment"># 想不到这个点title() 方法 竟然可以放到参数外边</span></span><br><span class="line">        print(msg)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">usernames = [<span class="string">'baka'</span>, <span class="string">'dage'</span>, <span class="string">'gogo'</span>]</span><br><span class="line">greet_user(usernames)</span><br><span class="line"><span class="comment"># Hello,Baka!</span></span><br><span class="line"><span class="comment"># Hello,Dage!</span></span><br><span class="line"><span class="comment"># Hello,Gogo!</span></span><br></pre></td></tr></table></figure>

<h4 id="禁止函数修改源列表，使用副本传入"><a href="#禁止函数修改源列表，使用副本传入" class="headerlink" title="禁止函数修改源列表，使用副本传入"></a>禁止函数修改源列表，使用副本传入</h4><p>直接使用副本传入，而不对源列表进行修改，省去了创建备份的工作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 参数名是切片的形式，传入的可以是切片之后的变量，传入之后不对原参数做修改</span></span><br><span class="line"><span class="comment"># 1使用切片传入2使用切片变量传入3测试传入切片变量是否会修改切片数据值</span></span><br><span class="line"><span class="comment"># 定义的时候不需要，传入的时候需要！！！</span></span><br><span class="line">list1 = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">delet</span><span class="params">(li_name)</span>:</span></span><br><span class="line">    <span class="comment"># 是否直接表示传入的就是副本？并不是，在调用时使用副本切片语法的才是（传入副本的正确姿势）</span></span><br><span class="line">    li_name.append(<span class="string">"makabaka"</span>)</span><br><span class="line">    <span class="comment"># 在这里边并不能使用 del 语句 成功删除变量</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">delet(list1[:])</span><br><span class="line">print(<span class="string">"以列表副本[:]传入的结果，list1="</span>, list1)</span><br><span class="line"><span class="comment"># 以列表副本[:]传入的结果，list1= [1, 2, 3, 4, 5, 6, 7, 8]</span></span><br><span class="line"><span class="comment"># 可以得出，对副本的操作不影响源列表</span></span><br><span class="line">delet(list1)</span><br><span class="line">print(<span class="string">"以列表名直接传入的结果，list1="</span>, list1)</span><br><span class="line"><span class="comment"># 以列表名直接传入的结果，list1= [1, 2, 3, 4, 5, 6, 7, 8, 'makabaka']</span></span><br><span class="line"><span class="comment"># 直接操作了源列表</span></span><br></pre></td></tr></table></figure>

<h3 id="传递任意数量的实参"><a href="#传递任意数量的实参" class="headerlink" title="传递任意数量的实参"></a>传递任意数量的实参</h3><p>括号是空元组，元素后加了逗号才能表达单元素元组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">person_list</span><span class="params">(*person_name)</span>:</span></span><br><span class="line">    <span class="comment"># 形参名中的星号让Python创建一个名为person_name的空元组，并将收到的所有值都封装到这个元祖中。</span></span><br><span class="line">    <span class="comment">#    print(person_name)</span></span><br><span class="line">    <span class="comment"># 使用的时候不用带星号</span></span><br><span class="line"></span><br><span class="line">    print(<span class="string">"参与的人员有："</span>)</span><br><span class="line">    <span class="comment"># 使用循环进行规整化输出</span></span><br><span class="line">    <span class="keyword">for</span> name <span class="keyword">in</span> person_name:</span><br><span class="line">        print(<span class="string">"&#123;&#125;"</span>.format(name).title())</span><br><span class="line">    print()  <span class="comment"># 空换行</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">person_list(<span class="string">'sudaqiang'</span>)</span><br><span class="line"><span class="comment"># ('sudaqiang',) 表示单元素元组的方式是 元素后加一个 逗号</span></span><br><span class="line">person_list(<span class="string">'naraii'</span>, <span class="string">'songxiaobao'</span>, <span class="string">'zhangyu'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 参与的人员有：</span></span><br><span class="line"><span class="comment"># Sudaqiang</span></span><br><span class="line"><span class="comment"># </span></span><br><span class="line"><span class="comment"># 参与的人员有：</span></span><br><span class="line"><span class="comment"># Naraii</span></span><br><span class="line"><span class="comment"># Songxiaobao</span></span><br><span class="line"><span class="comment"># Zhangyu</span></span><br></pre></td></tr></table></figure>

<h4 id="使用任意数量的关键字实参"><a href="#使用任意数量的关键字实参" class="headerlink" title="使用任意数量的关键字实参"></a>使用任意数量的关键字实参</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">build_profile</span><span class="params">(first, last, **user_info)</span>:</span></span><br><span class="line">    <span class="comment"># 形参中的两个星号意思是创建一个名为 user_info 的空字典</span></span><br><span class="line">    <span class="comment"># 并将所有收到的 名称-值对 都封装到这个字典中，接收数据时不是标准的键-值对模式，理解为一种转换（具体体现在封装这个操作</span></span><br><span class="line">    <span class="comment"># 将赋值语句中的变量和值转换为键值对性</span></span><br><span class="line">    <span class="string">"""创建一个字典，其中包含我们知道的有关用户的一切"""</span></span><br><span class="line">    profile = &#123;&#125;  <span class="comment"># 这是在函数中创建变量，思考思考思考思考</span></span><br><span class="line">    profile[<span class="string">'first_name'</span>] = first</span><br><span class="line">    profile[<span class="string">'last_name'</span>] = last</span><br><span class="line">    <span class="keyword">for</span> key, value <span class="keyword">in</span> user_info.items():</span><br><span class="line">        profile[key] = value</span><br><span class="line">    <span class="keyword">return</span> profile</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">user_profile = build_profile(</span><br><span class="line">    <span class="string">'albert'</span>, <span class="string">'einstein'</span>,</span><br><span class="line">    location=<span class="string">'princeton'</span>,</span><br><span class="line">    <span class="comment"># 这是传给任意数量的实参，注意 名称-值 对中，名称未加引号,同样是不可修改类型</span></span><br><span class="line">    <span class="comment"># 姑且称之为名称-值对，看起来更像是为变量赋值（一个赋值语句</span></span><br><span class="line">    field=<span class="string">'physics'</span></span><br><span class="line">)</span><br><span class="line">print(user_profile)</span><br><span class="line"><span class="comment"># &#123;'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="将函数存储在模块中"><a href="#将函数存储在模块中" class="headerlink" title="将函数存储在模块中"></a>将函数存储在模块中</h3><p>将函数存储在独立的文件中重复使用，知道如何导入函数，还能让你使用其他程序员编写的函数库</p>
<h4 id="导入整个模块，使用函数须加模块名"><a href="#导入整个模块，使用函数须加模块名" class="headerlink" title="导入整个模块，使用函数须加模块名"></a>导入整个模块，使用函数须加模块名</h4><p>名为 _34python.py 的模块</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">make_pizza</span><span class="params">(size, *toppings)</span>:</span>  <span class="comment"># topping,n,糕点上的装饰配料</span></span><br><span class="line">    <span class="string">"""概述要制作的pizza"""</span></span><br><span class="line">    print(<span class="string">"\nMaking a &#123;&#125;-inch pizza with the following toppings:"</span>.format(str(size)))</span><br><span class="line">    <span class="keyword">for</span> topping <span class="keyword">in</span> toppings:</span><br><span class="line">        print(<span class="string">"- &#123;&#125;"</span>.format(topping))</span><br></pre></td></tr></table></figure>

<p>引用示例</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 导入编写的模块</span></span><br><span class="line"><span class="keyword">import</span> _34function  <span class="comment"># 不可以用数字开头哦</span></span><br><span class="line"></span><br><span class="line">_34function.make_pizza(<span class="number">16</span>, <span class="string">'pepperoni'</span>)</span><br><span class="line">_34function.make_pizza(<span class="number">12</span>, <span class="string">'mushroom'</span>, <span class="string">'green peppers'</span>, <span class="string">'extra cheese'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># Making a 16-inch pizza with the following toppings:</span></span><br><span class="line"><span class="comment"># - pepperoni</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Making a 12-inch pizza with the following toppings:</span></span><br><span class="line"><span class="comment"># - mushroom</span></span><br><span class="line"><span class="comment"># - green peppers</span></span><br><span class="line"><span class="comment"># - extra cheese</span></span><br></pre></td></tr></table></figure>

<p>运行时会将模块中的所有函数都复制到这个程序中，你看不到，幕后复制</p>
<p>导入模块后使用其函数的语法：</p>
<ul>
<li>​    modul_name.function_name()</li>
</ul>
<h4 id="导入特定的函数，调用直接用"><a href="#导入特定的函数，调用直接用" class="headerlink" title="导入特定的函数，调用直接用"></a>导入特定的函数，调用直接用</h4><p>只使用一个小函数没必要把整个库都导入进来，可以使用下面的语法只导入模块的某个函数：</p>
<ul>
<li>from module_name import function_name,function_1,function_2….</li>
</ul>
<p>对于上一个案例可使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> _34function <span class="keyword">import</span> make_pizza</span><br></pre></td></tr></table></figure>

<p>如果使用这种语法，调用时就无需使用 点 。由于我们在 import 语句中显式地导入了函数make_pizza() ，相当于直接在导入处直接定义了，调用时指定其名称即可</p>
<h4 id="使用-as-给函数、模块指定别名"><a href="#使用-as-给函数、模块指定别名" class="headerlink" title="使用 as 给函数、模块指定别名"></a>使用 as 给函数、模块指定别名</h4><p>导入的函数或模块名称冲突或名称太长，可使用无二的别名，类似于外号，需要在导入时，在其后面追加 as new_name 即可。注意指定的对象，因为模块也支持这样的操作</p>
<h4 id="到入模块中的所有函数，直接用"><a href="#到入模块中的所有函数，直接用" class="headerlink" title="到入模块中的所有函数，直接用"></a>到入模块中的所有函数，直接用</h4><p>from module_name import *</p>
<p>这样会将该模块的每个函数都复制到这个程序文件中。由于导入了每个函数，可以直接通过名称直接调用（与到入模块的区别，调用时加不加模块名字和 句点）。不建议这么做，导入别人的模块时，可能与自己编写的函数名冲突。</p>
<p>最佳做法：</p>
<ul>
<li>只导入需要使用的函数</li>
<li>导入整个模块，调用时注意语法（modul_name.function_name()）</li>
</ul>
<h3 id="函数编写指南与章末小结"><a href="#函数编写指南与章末小结" class="headerlink" title="函数编写指南与章末小结"></a>函数编写指南与章末小结</h3><p>给函数是定描述性名称，且只用小写字母和下划线</p>
<p>定义后面应存在该函数简单的阐述，良好的文档可以使程序员快速掌握使用方法</p>
<p>给形参指定默认值时，等号两边不要有空格</p>
<p>代码行长尽量不要超过79个字符</p>
<p>所有的 import 都应放在开头，除非开头强调注释</p>
<h2 id="类"><a href="#类" class="headerlink" title="类"></a>类</h2><h3 id="创建类和使用类"><a href="#创建类和使用类" class="headerlink" title="创建类和使用类"></a>创建类和使用类</h3><h4 id="创建Dog类"><a href="#创建Dog类" class="headerlink" title="创建Dog类"></a>创建Dog类</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span><span class="params">()</span>:</span>  <span class="comment"># 1</span></span><br><span class="line">    <span class="string">"""一次模拟小狗的简单尝试"""</span>  <span class="comment"># 2</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name, age)</span>:</span>  <span class="comment"># 3</span></span><br><span class="line">        <span class="string">"""初始化属性name和age"""</span></span><br><span class="line">        self.name = name  <span class="comment"># 4</span></span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">sit</span><span class="params">(self)</span>:</span>  <span class="comment"># 5</span></span><br><span class="line">        <span class="string">"""模拟小狗被命令时蹲下"""</span></span><br><span class="line">        print(self.name.title() + <span class="string">" is now sitting."</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">roll_over</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""模拟小狗被命令时打滚"""</span></span><br><span class="line">        print(self.name.title() + <span class="string">" rolled over!"</span>)</span><br></pre></td></tr></table></figure>

<p>以下解释大多整理与书中：<br>在1处，我们定义了一个名为Dog的类。类的首字母需要大写。括号是空的，暂不解释</p>
<p>在2处，编写了一个文档字符串，对类的功能进行了简单的描述</p>
<h5 id="1-方法-init"><a href="#1-方法-init" class="headerlink" title="1.方法_ _ init _ _()"></a>1.方法_ _ init _ _()</h5><p><strong>类中的函数称为方法</strong>。前面学到的关于函数的一切都适用于方法，就现在而言，唯一重要的差别是调用方法的方式。</p>
<p>在3处的方法 _ _ init _ _() 是一个特殊的方法，每当你根据Dog类创建新的实例时，Python都会自动运行它。在这个方法的名称中，开头末尾各有两个下划线，这是一种约定，旨在避免Python默认方法与普通方法发生名称冲突。</p>
<p>我们将方法_ _ init _ _ ()定义成了包含三个形参：self、name、age。在这个方法的定义中，形参self必不可少，还必须位于其他形参的前面。为何必须在方法定义中包含形参self呢？因为Python点用这个 _ _ init _ _ () 方法来创建Dog实例时，将自动传入实参self。<em>每个与类相关联的方法调用都自动传递实参self，它是一个指向实例本身得引用，让实例能够访问类中的属性和方法。</em>我们创建Dog实例时，Python将调用Dog类的方法 _ _ init _ _ () 。我们将通过实参向Dog() 传递名字和年龄，self会自动传递，因此我们不需要传递它。每当我们根据Dog类创建实例时，都只需给最后两个形参(name和age)提供值。</p>
<p>在4处定义的两个变量都有前缀self。以self 为前缀的变量都可供类中的所有方法使用，我们还可以通过类的任何实例来访问这些变量。self.name = name获取存储在形参name中的值，并将其存储到变量name中，然后该变量被关联到当前创建的实例。<strong>像这样可以通过实例访问的变量称为属性</strong></p>
<p>在5处，Dog类还定义了另外两个方法：sit() 和 roll_over()。由于这些方法不需要额外的信息，如名字和年龄，因此他们只有一个形参self。后面我们将创建的实例能够访问这些方法，换句话说，他们都会蹲下和打滚。当前，sit() 和 roll_over() 所做的有限，它们只是打印一条消息，指出小狗正蹲下或打滚。但可以扩展这些方法以模拟实际情况：如果这个类包含在一个计算机游戏中，这些方法将包含创建小狗蹲下和打滚动画效果的代码。如果这个类是用于控制机器狗的，这些方法将引导机器狗做出下蹲和打滚的动作。</p>
<h4 id="根据类创建实例（instance，n，实例）"><a href="#根据类创建实例（instance，n，实例）" class="headerlink" title="根据类创建实例（instance，n，实例）"></a>根据类创建实例（instance，n，实例）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Class Dog():</span><br><span class="line">    --这里使用我们前边定义的类--</span><br><span class="line">my_dog = Dog(<span class="string">'willie'</span>, <span class="number">6</span>)  <span class="comment"># 6</span></span><br><span class="line">print(<span class="string">"My dog's name is &#123;&#125;."</span>.format(my_dog.name.title()))  <span class="comment"># 7</span></span><br><span class="line">print(<span class="string">"My dog is &#123;&#125; years old."</span>.format(str(my_dog.age)))  <span class="comment"># 8</span></span><br><span class="line"><span class="comment"># My dog's name is Willie.</span></span><br><span class="line"><span class="comment"># My dog is 6 years old.</span></span><br></pre></td></tr></table></figure>

<p>在6处，我们让Python创建了一条名为’willie’年龄为6的小狗。遇到这行代码时，Python使用’willie’和6调用Dog类中的方法 _ _ init _ _ () 。该方法创建一个表示特定小狗的实例，并使用我们提供的值来设置属性name和age。方法 _ _ init _ _ () 并未显式的包含 return 语句，但Python自动返回一个表示这条小狗的实例。我们将这个实力存储在变量 my_dog 中。注意这里的命名约定，Dog指的是类，my_dog指的是根据类创建的实例。</p>
<h5 id="1-访问属性"><a href="#1-访问属性" class="headerlink" title="1.访问属性"></a>1.访问属性</h5><p><strong>要访问类的属性，可使用句点表示法。</strong>在7处，我们编写了如下代码来访问my_dog的属性name的值：my_dog.name  。句点表示法在Python中很常见，这种语法演示了Python如何获悉属性的值。此处，Python先找到实例my_dog，再查找与这个实例相关联的属性name。在Dog类中引用这个属性时，使用的是self.name 。在8处我们使用同样的方法来获取属性name的值。</p>
<h5 id="2-调用方法"><a href="#2-调用方法" class="headerlink" title="2.调用方法"></a>2.调用方法</h5><p>同样是使用句点表示法来调用Dog类中定义的任何方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">my_dog.sit()</span><br><span class="line">my_dog.roll_over()</span><br><span class="line"><span class="comment"># Willie is now sitting.</span></span><br><span class="line"><span class="comment"># Willie rolled over!</span></span><br></pre></td></tr></table></figure>

<p>注意这里是根据my_dog来barabara，<u>是否是Dog类已经被实例化到my_dog，然后可以通过my_dog来调用对应的方法？是</u>，要调用方法，可指定实例的名称（此处是my _dog）和要调用的方法，并用句点来分隔他们。遇到代码my_dog.sit()时，Python在类Dog中查找方法sit() 并运行其代码。Python以同样的方式解读代码my_dog.roll_over() 。</p>
<p>这种语法很有用。如果给属性和方法制定了合适的描述性名称，如name、age、sit() 、roll_over() ，即使是从未见过的代码块，也可以轻松推断出是做什么的。</p>
<h5 id="3-创建多个实例"><a href="#3-创建多个实例" class="headerlink" title="3.创建多个实例"></a>3.创建多个实例</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span><span class="params">()</span>:</span></span><br><span class="line">--省略--</span><br><span class="line">my_dog=Dog(<span class="string">'willie'</span>,<span class="number">6</span>)</span><br><span class="line">my_dog.sit()</span><br><span class="line">my_dog.roll_over()</span><br><span class="line"><span class="comment"># Willie is now sitting.</span></span><br><span class="line"><span class="comment"># Willie rolled over!</span></span><br><span class="line">your_dog=Dog(<span class="string">'lucy'</span>,<span class="number">3</span>)</span><br><span class="line">your_dog.sit()</span><br><span class="line">your_dog.roll_over()</span><br><span class="line"><span class="comment"># Lucy is now sitting.</span></span><br><span class="line"><span class="comment"># Lucy rolled over!</span></span><br></pre></td></tr></table></figure>

<h3 id="使用类和实例"><a href="#使用类和实例" class="headerlink" title="使用类和实例"></a>使用类和实例</h3><h4 id="Car类"><a href="#Car类" class="headerlink" title="Car类"></a>Car类</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""一次模拟汽车的简单尝试"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, make, model, year)</span>:</span></span><br><span class="line">        self.make = make</span><br><span class="line">        self.model = model</span><br><span class="line">        self.year = year</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_descriptive_name</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""返回整洁的描述性信息"""</span></span><br><span class="line">        long_name = str(self.year) + <span class="string">' '</span> + self.make + <span class="string">' '</span> + self.model</span><br><span class="line">        <span class="keyword">return</span> long_name.title()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">my_new_car = Car(<span class="string">'audi'</span>, <span class="string">'a4'</span>, <span class="number">2016</span>)</span><br><span class="line">print(my_new_car.get_descriptive_name())</span><br></pre></td></tr></table></figure>

<h4 id="给属性指定默认值"><a href="#给属性指定默认值" class="headerlink" title="给属性指定默认值"></a>给属性指定默认值</h4><p>类中的每个属性都必须有初始值，哪怕这个值是0或空字符串。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""一次模拟汽车的简单尝试"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, make, model, year)</span>:</span></span><br><span class="line">        self.make = make</span><br><span class="line">        self.model = model</span><br><span class="line">        self.year = year</span><br><span class="line"><span class="comment"># 下面是里程数初始化</span></span><br><span class="line">        self.odometer_reading = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">read_odometer</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""打印一条汽车里程的消息"""</span></span><br><span class="line">        print(<span class="string">"This car has "</span> + str(self.odometer_reading) + <span class="string">" miles on it"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_descriptive_name</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""返回整洁的描述性信息"""</span></span><br><span class="line">        long_name = str(self.year) + <span class="string">' '</span> + self.make + <span class="string">' '</span> + self.model</span><br><span class="line">        <span class="keyword">return</span> long_name.title()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">my_new_car = Car(<span class="string">'audi'</span>, <span class="string">'a4'</span>, <span class="number">2016</span>)</span><br><span class="line">print(my_new_car.get_descriptive_name())</span><br><span class="line">my_new_car.read_odometer()</span><br></pre></td></tr></table></figure>

<h4 id="修改属性的值"><a href="#修改属性的值" class="headerlink" title="修改属性的值"></a>修改属性的值</h4><ol>
<li>直接通过实例进行修改</li>
<li>通过方法进行设置</li>
<li>通过方法进行递增</li>
</ol>
<h5 id="1-直接修改属性的值"><a href="#1-直接修改属性的值" class="headerlink" title="1.直接修改属性的值"></a>1.直接修改属性的值</h5><p>通过实例访问它，然后修改</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">my_new_car.odometer_reading = <span class="number">23</span></span><br><span class="line">my_new_car.read_odometer()</span><br><span class="line"><span class="comment"># This car has 23 miles on it</span></span><br></pre></td></tr></table></figure>

<h5 id="2-通过方法修改"><a href="#2-通过方法修改" class="headerlink" title="2.通过方法修改"></a>2.通过方法修改</h5><p>这里的参数并没有在 _ _ init _ _ () 里的括号里存在，而是在下面定义的专属方法的参数表里。可见类不一定要一次性接受所有参数，其内部的方法可以独立选择传入的参数，当然这需要在 _ _ init _ _ () 里初始化（暂时未出现在参数表里进行初始化的）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">my_new_car.update_odometer(<span class="number">56</span>)</span><br><span class="line">my_new_car.read_odometer()</span><br><span class="line"><span class="comment"># This car has 56 miles on it</span></span><br></pre></td></tr></table></figure>

<p>禁止回调里程数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span><span class="params">()</span>:</span></span><br><span class="line">    --省略--</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">update_odometer</span><span class="params">(self, mileage)</span>:</span>  <span class="comment"># mileage,n,英里数</span></span><br><span class="line">        <span class="string">"""加一个禁止回调的逻辑"""</span></span><br><span class="line">        <span class="keyword">if</span> mileage&gt;= self.odometer_reading:</span><br><span class="line">            self.odometer_reading = mileage</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">"You can't roll back an odometer!"</span>)</span><br><span class="line">my_new_car.update_odometer(<span class="number">56</span>)</span><br><span class="line">my_new_car.read_odometer()</span><br><span class="line">my_new_car.update_odometer(<span class="number">0</span>)</span><br><span class="line">my_new_car.read_odometer()</span><br><span class="line"><span class="comment"># This car has 56 miles on it</span></span><br><span class="line"><span class="comment"># You can't roll back an odometer!</span></span><br><span class="line"><span class="comment"># This car has 56 miles on it</span></span><br></pre></td></tr></table></figure>

<h5 id="3-通过方法对属性的值进行递增"><a href="#3-通过方法对属性的值进行递增" class="headerlink" title="3.通过方法对属性的值进行递增"></a>3.通过方法对属性的值进行递增</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span><span class="params">()</span>:</span></span><br><span class="line">    --省略--</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">increment_odometer</span><span class="params">(self,miles)</span>:</span></span><br><span class="line">        <span class="string">"将里程表的读数进行增加指定的量"</span></span><br><span class="line">        self.odometer_reading+=miles</span><br><span class="line">my_new_car.increment_odometer(<span class="number">10</span>)</span><br><span class="line">my_new_car.read_odometer()</span><br><span class="line"><span class="comment"># This car has 66 miles on it</span></span><br></pre></td></tr></table></figure>

<p>另外可以自己实现一个防止利用负数来修改里程表的案例</p>
<h3 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h3><p>编写类时，并非总是要从空白开始。如果你要编写的类是类一个现成类的特殊版本，可使用继承。继承所有的属性和方法。以父类子类称呼。另外子类还可以定义自己的属性和方法。</p>
<h4 id="子类的方法-init"><a href="#子类的方法-init" class="headerlink" title="子类的方法 _ _ init _ _ ()"></a>子类的方法 _ _ init _ _ ()</h4><p>创建子类的实例时，需要完成父类的所有属性赋值。为此，子类的方法 _ _ init _ _ () 需要父类施以援手。</p>
<p>ElectricCar：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, make, model, year)</span>:</span></span><br><span class="line">        self.make = make</span><br><span class="line">        self.model = model</span><br><span class="line">        self.year = year</span><br><span class="line">        self.odometer_reading = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_descriptive_name</span><span class="params">(self)</span>:</span></span><br><span class="line">        long_name = str(self.year) + <span class="string">' '</span> + self.make + <span class="string">' '</span> + self.model</span><br><span class="line">        <span class="keyword">return</span> long_name.title()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">read_odometer</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"这车开了&#123;&#125;这么远"</span>.format(self.odometer_reading))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">update_odometer</span><span class="params">(self, mileage)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> mileage &gt;= self.odometer_reading:</span><br><span class="line">            self.odometer_reading = mileage</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">"你怎么敢回调里程数？"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">increment_odometer</span><span class="params">(self, miles)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> miles &gt;= <span class="number">0</span>:</span><br><span class="line">            self.odometer_reading += miles</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">"想篡改？给爷爬！"</span>)</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ElectricCar</span><span class="params">(Car)</span>:</span></span><br><span class="line">    <span class="string">"""电动汽车理所当然是汽车的子类"""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,make,model,year)</span>:</span></span><br><span class="line">        <span class="string">"""初始化父类的属性"""</span></span><br><span class="line">        super().__init__(make,model,year)</span><br><span class="line">my_tesla=ElectricCar(<span class="string">'tesla'</span>,<span class="string">'model s'</span>,<span class="number">2016</span>)</span><br><span class="line">print(my_tesla.get_descriptive_name())</span><br></pre></td></tr></table></figure>

<p>创建子类时，父类必须包含在当前文件中，且位于子类的前面。</p>
<p>定义子类时，必须在括号内指定父类的名称。</p>
<p>方法 _ _ init _ _ () 接受创建Car实例所需的所有信息。</p>
<p>这里的super() 是一个特殊的函数，将父类和子类关联起来。让子类的实例包含了父类的所有属性（父类也叫superclass，super因此得名）</p>
<h4 id="给子类定义属性和方法"><a href="#给子类定义属性和方法" class="headerlink" title="给子类定义属性和方法"></a>给子类定义属性和方法</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">    --省略--</span><br><span class="line">    super().__init__(make, model, year)</span><br><span class="line">    <span class="string">"""子类的变量初始化在super下面"""</span></span><br><span class="line">    self.battery_size = <span class="number">70</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">describe_battery</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""打印一条描述电瓶容量的信息"""</span></span><br><span class="line">    print(<span class="string">"这车有一个&#123;&#125;-kWh的电池"</span>.format(self.battery_size))</span><br><span class="line">    </span><br><span class="line">my_tesla.describe_battery()</span><br><span class="line"><span class="comment"># 这车有一个70-kWh的电池</span></span><br></pre></td></tr></table></figure>

<h4 id="重写父类方法"><a href="#重写父类方法" class="headerlink" title="重写父类方法"></a>重写父类方法</h4><p>大概是一种覆盖的思想，并不再回去把父类源文件改了，而是在子类中使用相同的方法名来重写。Python将关注子类中的定义的相应的方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">--省略--</span><br><span class="line"><span class="comment"># 假设汽车里面定义了油箱这个方法，但是电车就需要重写</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">fill_gas_tank</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""描述电车的邮箱"""</span></span><br><span class="line">        print(<span class="string">"该电车没有油箱！"</span>)</span><br><span class="line">    </span><br><span class="line">    my_tesla.fill_gas_tank()</span><br><span class="line"><span class="comment"># 该电车没有油箱！</span></span><br></pre></td></tr></table></figure>

<h4 id="将实例用作属性"><a href="#将实例用作属性" class="headerlink" title="将实例用作属性"></a>将实例用作属性</h4><p>大类拆分为多个协同工作的小类，类中类！</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, car_name)</span>:</span></span><br><span class="line">        self.car_name = car_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">car_description</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"这辆车的型号是：&#123;&#125;"</span>.format(self.car_name))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Battery</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, battery_size=<span class="number">70</span>)</span>:</span></span><br><span class="line">        <span class="string">"""初始化电瓶属性，并且见识到了可以在参数表内初始化"""</span></span><br><span class="line">        self.battery_size = battery_size</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">describe_battery</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"这个电车有一个&#123;&#125;-kWh的电池。"</span>.format(str(self.battery_size)))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 以上简单定义了，车与电池两个大类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ElectrcCar</span><span class="params">(Car)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, car_name)</span>:</span></span><br><span class="line">        <span class="string">"""初始化父类属性"""</span></span><br><span class="line">        super().__init__(car_name)</span><br><span class="line">        <span class="comment"># 以上的初始化没有加入self，因为上面def后跟的是电车的self，这里只需要关联汽车的其他属性即可</span></span><br><span class="line">        <span class="string">"""再初始化特有属性"""</span></span><br><span class="line">        self.battery = Battery()</span><br><span class="line">        <span class="comment"># 竟然直接用了一个类作为属性值</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">my_tesla = ElectrcCar(<span class="string">'Model S'</span>)</span><br><span class="line"><span class="comment"># print(my_tesla.car_description())</span></span><br><span class="line"><span class="comment"># 经常出现 None 的原因，实例调用方法之后已经输出信息了，再来一个print就输出为空！</span></span><br><span class="line">my_tesla.car_description()</span><br><span class="line">my_tesla.battery.describe_battery()  <span class="comment"># 震惊！这样的连写竟然就是类中类！</span></span><br><span class="line"><span class="comment"># 这辆车的型号是：Model S</span></span><br><span class="line"><span class="comment"># 这个电车有一个70-kWh的电池。</span></span><br></pre></td></tr></table></figure>

<p>现在每创建一个ElectricCar实例都包含一个自动创建的Battery实例</p>
<h4 id="模拟实物"><a href="#模拟实物" class="headerlink" title="模拟实物"></a>模拟实物</h4><p>现实世界的建模方法没有对错之分。应从更高维度来思考事物的组成，需要多次尝试，去追求更高效、准确的代码，永不气馁！</p>
<h3 id="导入类"><a href="#导入类" class="headerlink" title="导入类"></a>导入类</h3><h4 id="导入单个类"><a href="#导入单个类" class="headerlink" title="导入单个类"></a>导入单个类</h4><p>将Car类存储在一个名为car.py的模块中，从现在开始，使用该模块的程序都必须使用更具体的文件名</p>
<p>my_new_car.py：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> _40car <span class="keyword">import</span> Car</span><br><span class="line">my_new_car=Car(<span class="string">'tesla'</span>,<span class="string">'model s'</span>,<span class="string">'2020'</span>)</span><br><span class="line">print(my_new_car.get_descriptive_name())</span><br><span class="line"><span class="comment"># 2020 Tesla Model S</span></span><br><span class="line">my_new_car.odometer_reading=<span class="number">23</span></span><br><span class="line">my_new_car.read_odometer()</span><br><span class="line"><span class="comment"># This car has 23 miles on it</span></span><br></pre></td></tr></table></figure>

<h4 id="在一个模块中存储多个类"><a href="#在一个模块中存储多个类" class="headerlink" title="在一个模块中存储多个类"></a>在一个模块中存储多个类</h4><ul>
<li>如电池和电车都可以帮助模拟汽车，所以可以将他们都加入到Car.py</li>
<li>然后建立一个新的电车实例，就可以直接导入一个汽车类来实现各种行为。</li>
</ul>
<h4 id="从一个模块中导入多个类，访问类直接用"><a href="#从一个模块中导入多个类，访问类直接用" class="headerlink" title="从一个模块中导入多个类，访问类直接用"></a>从一个模块中导入多个类，访问类直接用</h4><p><strong>from model_file_name import Class1,Class2……</strong></p>
<p>这种类的导入方式，在后续代码可以直接创建实例</p>
<h4 id="导入整个模块，访问类须加模块名"><a href="#导入整个模块，访问类须加模块名" class="headerlink" title="导入整个模块，访问类须加模块名"></a>导入整个模块，访问类须加模块名</h4><p>这种导入方式，需要用句点表示法来说明需要访问的类，方法简单，易于阅读。由于类的使用都包含了模块名，因此不会与当前文件使用的任何名称发生冲突。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> _40car</span><br><span class="line"></span><br><span class="line">my_bettle = _40car.Car(<span class="string">'audi'</span>, <span class="string">'a4'</span>, <span class="string">'2016'</span>)</span><br><span class="line">print(my_bettle.get_descriptive_name())</span><br><span class="line"><span class="comment"># 2016 Audi A4</span></span><br><span class="line">my_tesla = _40car.ElectricCar(<span class="string">'tesla'</span>, <span class="string">'roadster'</span>, <span class="number">2020</span>)</span><br><span class="line">print(my_tesla.get_descriptive_name())</span><br><span class="line"><span class="comment"># 2020 Tesla Roadster</span></span><br></pre></td></tr></table></figure>

<h4 id="导入模块中的所有类"><a href="#导入模块中的所有类" class="headerlink" title="导入模块中的所有类"></a>导入模块中的所有类</h4><p>使用下面的语法，导入模块中的所有类：</p>
<p><strong>from mudle_file_name import *</strong></p>
<p>不推荐这种方法：</p>
<ol>
<li>如果只看一下开头的import语句，就能知道程序用了啥，那将会很好。但是这种直接全部搬过来，没有明确指出，引发困惑！</li>
<li>一旦导入了一个与程序文件中其他东西同名的类，这将引发难以诊断的错误！</li>
</ol>
<p>需要从一个模块导入许多类时，最好使用这种方法导入整个模块。</p>
<h4 id="在一个模块中导入另一个模块"><a href="#在一个模块中导入另一个模块" class="headerlink" title="在一个模块中导入另一个模块"></a>在一个模块中导入另一个模块</h4><p>类分散到了多个模块以后，可能会形成依赖。这种情况下，可在前一个模块中导入必要的类。</p>
<p>Car作为模块1，ElectricCar和Battery作为模块2</p>
<p>在使用模块2来创建实例之前，必须先导入电车的父类模块</p>
<p>模块2：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> _40car <span class="keyword">import</span> Car</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ElectricCar</span><span class="params">(Car)</span>:</span></span><br><span class="line"></span><br><span class="line">--省略--</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Battery</span><span class="params">()</span>:</span></span><br><span class="line"></span><br><span class="line">--省略--</span><br></pre></td></tr></table></figure>

<p>然后在其他程序直接导入模块2 或者所需内容即可</p>
<h4 id="自定义工作流程"><a href="#自定义工作流程" class="headerlink" title="自定义工作流程"></a>自定义工作流程</h4><ul>
<li>一开始应让代码解构尽可能简单。先尽可能在一个文件夹中完成所有工作，一切都能正常运行后，再将类移动到独立的模块中。、</li>
<li>如果你喜欢模块和文件的交互方式，可尝试在项目开始时就将类存储到模块中。</li>
<li>先找出让你能够编写出可行代码的方式，再尝试让代码更为最值有序</li>
</ul>
<h3 id="Python标准库"><a href="#Python标准库" class="headerlink" title="Python标准库"></a>Python标准库</h3><p>Python的标准库是一组模块，安装的Python都包含它。</p>
<p>比如要记录字典中键-值对的添加顺序，可以使用模块collections中的OrderedDict类。OrderedDict实例的行为几乎与字典相同，区别只在于记录了键-值对的添加顺序。</p>
<p>这个类直接实例化得到的是空的有序字典</p>
<h3 id="类编码风格"><a href="#类编码风格" class="headerlink" title="类编码风格"></a>类编码风格</h3><ul>
<li>类名采用(大)驼峰命名法</li>
<li>实例名和模块名都采用小写格式，并在单词之间加上下划线。</li>
<li>每个类后面都应紧跟一个文档字符串，每个模块也是。简要的描述功能。</li>
<li>空行的使用：<ul>
<li>在类中，一个空行分隔方法</li>
<li>在模块中，两个空行分隔类</li>
</ul>
</li>
<li>导入模块时，先写标准库模块，空行，再写自己的模块</li>
</ul>
<h3 id="小结-1"><a href="#小结-1" class="headerlink" title="小结"></a>小结</h3><p>多理解几遍 _ _ init _ _ ()、self、super()</p>
<p>这个章节建议多刷点题，去力扣。</p>
<p><strong>总结写导入方法，无论是函数还是类，只要语句含有from，就可以直接使用，否则使用句点表示法</strong></p>
<h2 id="文件和异常"><a href="#文件和异常" class="headerlink" title="文件和异常"></a>文件和异常</h2><h3 id="从文件中读取数据"><a href="#从文件中读取数据" class="headerlink" title="从文件中读取数据"></a>从文件中读取数据</h3><h4 id="读取整个文件"><a href="#读取整个文件" class="headerlink" title="读取整个文件"></a>读取整个文件</h4><p>新建一个文件，包含圆周率30位，小数点后每十位换行，命名为_41_pi.txt</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 关键字with 在不再需要访问文件后将其关闭</span></span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'_41_pi.txt'</span>) <span class="keyword">as</span> file_object:</span><br><span class="line">    <span class="comment"># 使用 open() 打开文件，使用 as 语法创建别名</span></span><br><span class="line">    contens = file_object.read()</span><br><span class="line">    <span class="comment"># 使用变量存储通过 read() 方法读取的数据</span></span><br><span class="line">    print(contens)</span><br></pre></td></tr></table></figure>

<p>我们调用了open但没有调用close()，可能会出现关早了或关晚了的bug。如果使用with，Python会自动选择关闭时机。</p>
<h5 id="文件路径"><a href="#文件路径" class="headerlink" title="文件路径"></a>文件路径</h5><ul>
<li>未指定路径的话，Python会在当前程序文件所属目录来寻找。</li>
<li>相对路径，目前书上只写了向同级之内来寻找，使用反（捺）斜杠，来指定文件路径，精确到文件后缀</li>
<li>绝对路径，从盘符开始写起也是用 反（捺）斜杠，精确到文件后缀</li>
</ul>
<h4 id="逐行读取"><a href="#逐行读取" class="headerlink" title="逐行读取"></a>逐行读取</h4><p>结合 for() 使用，</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">filename=<span class="string">'_41_pi.txt'</span></span><br><span class="line"><span class="keyword">with</span> open(filename) <span class="keyword">as</span> file_object:</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> file_object:</span><br><span class="line">        print(line)</span><br></pre></td></tr></table></figure>

<h4 id="创建一个包含文件行内容的列表"><a href="#创建一个包含文件行内容的列表" class="headerlink" title="创建一个包含文件行内容的列表"></a>创建一个包含文件行内容的列表</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">filename=<span class="string">'_41_pi.txt'</span></span><br><span class="line"><span class="keyword">with</span> open(filename) <span class="keyword">as</span> file_object:</span><br><span class="line">    lines = file_object.readlines()</span><br><span class="line">    <span class="comment"># readlines() 方法返回的是一个列表,文件的每一行是它的每一个元素，并且会追加换行符</span></span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> lines:</span><br><span class="line">    print(line)</span><br></pre></td></tr></table></figure>

<h4 id="包含1-000-000位的大文件"><a href="#包含1-000-000位的大文件" class="headerlink" title="包含1,000,000位的大文件"></a>包含1,000,000位的大文件</h4><p>尝试处理这种大文件，但是我们先只显示它的前50位：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">filename = <span class="string">'ex_file\prentend_pi.txt'</span></span><br><span class="line"><span class="keyword">with</span> open(filename) <span class="keyword">as</span> file_object:</span><br><span class="line">    lines = file_object.readlines()</span><br><span class="line">    <span class="comment"># 文件中的每一行作为 列表lines 的一个元素</span></span><br><span class="line">pi_string = <span class="string">''</span></span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> lines:</span><br><span class="line">    pi_string += line.strip()</span><br><span class="line">print(pi_string[:<span class="number">52</span>] + <span class="string">'......'</span>)  <span class="comment"># 这个52是因为3和小数点</span></span><br><span class="line">print(len(pi_string))</span><br></pre></td></tr></table></figure>

<h4 id="圆周率中包含你的生日吗"><a href="#圆周率中包含你的生日吗" class="headerlink" title="圆周率中包含你的生日吗"></a>圆周率中包含你的生日吗</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">filename = <span class="string">'ex_file\prentend_pi.txt'</span></span><br><span class="line"><span class="keyword">with</span> open(filename) <span class="keyword">as</span> file_object:</span><br><span class="line">    lines = file_object.readlines()</span><br><span class="line">    <span class="comment"># 文件中的每一行作为 列表lines 的一个元素</span></span><br><span class="line">pi_string = <span class="string">''</span></span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> lines:</span><br><span class="line">    pi_string += line.strip()</span><br><span class="line">print(pi_string[:<span class="number">52</span>] + <span class="string">'......'</span>)  <span class="comment"># 这个52是因为3和小数点</span></span><br><span class="line">print(len(pi_string))</span><br><span class="line">birthday=input(<span class="string">"输入你生日的八位数字，年年月月日日"</span>)</span><br><span class="line"><span class="keyword">if</span> birthday <span class="keyword">in</span> pi_string:</span><br><span class="line">    print(<span class="string">"你生在里圆周率里！"</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    print(<span class="string">"你没生到圆周率里！"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="写入文件"><a href="#写入文件" class="headerlink" title="写入文件"></a>写入文件</h3><h4 id="写入空文件-write-方法"><a href="#写入空文件-write-方法" class="headerlink" title="写入空文件 write() 方法"></a>写入空文件 write() 方法</h4><p>你在调用open时，需要提供另外一个实参，告诉Python你要写入打开的文件。</p>
<ul>
<li>w，写入，没有就新建，存在就覆盖(返回文件对象前清空)！</li>
<li>r，读取</li>
<li>a，附加</li>
<li>r+，读写</li>
<li>省略，只读</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">filename = <span class="string">'ex_file\prentend_pi.txt'</span></span><br><span class="line"><span class="keyword">with</span> open(filename) <span class="keyword">as</span> file_object:</span><br><span class="line">    lines = file_object.readlines()</span><br><span class="line">    <span class="comment"># 文件中的每一行作为 列表lines 的一个元素</span></span><br><span class="line">pi_string = <span class="string">''</span></span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> lines:</span><br><span class="line">    pi_string += line.strip()</span><br><span class="line">print(pi_string[:<span class="number">52</span>] + <span class="string">'......'</span>)  <span class="comment"># 这个52是因为3和小数点</span></span><br><span class="line">print(len(pi_string))</span><br><span class="line">birthday = input(<span class="string">"输入你生日的八位数字，年年月月日日"</span>)</span><br><span class="line"><span class="keyword">if</span> birthday <span class="keyword">in</span> pi_string:</span><br><span class="line">    print(<span class="string">"你生在里圆周率里！"</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'a'</span>) <span class="keyword">as</span> bir:</span><br><span class="line">        bir.write(birthday)</span><br><span class="line">    print(<span class="string">"你没生到圆周率里！"</span>)</span><br><span class="line">    <span class="comment"># 第二次你就生在圆周率里了</span></span><br><span class="line">    <span class="comment"># 看吧，这个生日被我们滑稽的追加到了文件里</span></span><br></pre></td></tr></table></figure>

<p>没有明确说明加入换行符的话，输出到文件的字符串不会因为在操作时用多个print而换行，如果需要的话请自行在字符串后面追加</p>
<h3 id="异常"><a href="#异常" class="headerlink" title="异常"></a>异常</h3><h4 id="处理ZeroDivisionError（零除错误）"><a href="#处理ZeroDivisionError（零除错误）" class="headerlink" title="处理ZeroDivisionError（零除错误）"></a>处理ZeroDivisionError（零除错误）</h4><p>ZeroDivisionError是一个异常对象，程序无法按你的要求做时，就会创建这种对象。</p>
<h4 id="使用-try-except-代码块"><a href="#使用-try-except-代码块" class="headerlink" title="使用 try-except 代码块"></a>使用 try-except 代码块</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    print(<span class="number">5</span>/<span class="number">0</span>)</span><br><span class="line"><span class="keyword">except</span> ZeroDivisionError:</span><br><span class="line">    print(<span class="string">"你他娘的不能用零做除数！"</span>)</span><br></pre></td></tr></table></figure>

<p>这样用户看到的是一条有好的错误消息，而不是回溯(traceback)</p>
<p>程序崩溃可不好，如果被怀有恶意的用户看到，他可能知道你的程序的文件名称，还将看到不能够正确运行的代码。训练有素的攻击者可能根据这些信息判断出可对你的代码发起什么样的攻击！</p>
<h4 id="else代码块"><a href="#else代码块" class="headerlink" title="else代码块"></a>else代码块</h4><p>依赖于try代码块成功执行的代码块都应该放到else代码块中：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    print(<span class="number">5</span>/<span class="number">2</span>)</span><br><span class="line"><span class="keyword">except</span> ZeroDivisionError:</span><br><span class="line">    print(<span class="string">"你他娘的不能用零做除数！"</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    print(<span class="string">"处理完毕！"</span>)</span><br></pre></td></tr></table></figure>

<p>try-except-else代码块的工作原理大致如下：</p>
<ol>
<li>尝试执行try代码块中的代码，只有可能引发异常的代码才需要放在try语句中。</li>
<li>有时候，有一些仅在try代码块成功执行时才需要运行的代码，需要放在else代码块中</li>
<li>except代码块告诉Python，如果它尝试运行try中的代码块时引发了指定的一场，会执行该部分的代码块</li>
</ol>
<p>猜测每个traceback错误都可以放在except中吧</p>
<h4 id="处理FileNotFoundError异常"><a href="#处理FileNotFoundError异常" class="headerlink" title="处理FileNotFoundError异常"></a>处理FileNotFoundError异常</h4><p>应该改就是我上面的猜测了，多收集些这样的异常，并写出对应方案，可以帮助避免代码泄露什么的</p>
<h4 id="分析文本"><a href="#分析文本" class="headerlink" title="分析文本"></a>分析文本</h4><p>处理英文读物中的单词数目，barabara，统计段落，词组什么的</p>
<p>这里需要熟悉几个方法：</p>
<ul>
<li>split() 以指定分隔符拆分字符串，返回列表</li>
</ul>
<h4 id="使用多个文件"><a href="#使用多个文件" class="headerlink" title="使用多个文件"></a>使用多个文件</h4><p>将我们处理信息的代码写成函数，注意规范注释。</p>
<h4 id="失败时不吭一声"><a href="#失败时不吭一声" class="headerlink" title="失败时不吭一声"></a>失败时不吭一声</h4><p>并非每次捕获异常都要说出来，有时候你希望程序在发生异常时一声不吭，就像什么都咩有发生过一样继续运行。大概思路就是在except指定的异常下；代码块内容为pass</p>
<h4 id="决定报告那些错误"><a href="#决定报告那些错误" class="headerlink" title="决定报告那些错误"></a>决定报告那些错误</h4><p>某些错误需要讲出来，某些错误需要闭一只眼，哈哈哈哈哈哈</p>
<h3 id="存储数据"><a href="#存储数据" class="headerlink" title="存储数据"></a>存储数据</h3><p>用户关闭程序，但是有数据需要保存，一种简单的方式是使用模块json来存储数据。json文件在编程语言中貌似通用性很高</p>
<p>JSON（JavaScript Object Notation）</p>
<h4 id="使用json-dump-和-json-load"><a href="#使用json-dump-和-json-load" class="headerlink" title="使用json.dump() 和 json.load()"></a>使用json.dump() 和 json.load()</h4><p>dump，vt，倾倒</p>
<p>第一个参数是从哪来，第二个参数是到哪去</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"></span><br><span class="line">numbers = [<span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">13</span>]</span><br><span class="line"></span><br><span class="line">filename = <span class="string">'ex_file\\numbers.json'</span></span><br><span class="line"><span class="comment"># 我傻了，竟然忘记这里需要忽略掉转移序列</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> open(filename, <span class="string">'w'</span>) <span class="keyword">as</span> f_obj:</span><br><span class="line">    json.dump(numbers, f_obj)</span><br><span class="line"><span class="comment"># 加载json</span></span><br><span class="line">file_name=<span class="string">'ex_file\\numbers.json'</span></span><br><span class="line"><span class="keyword">with</span> open(file_name) <span class="keyword">as</span> num_obj:</span><br><span class="line">    nums=json.load(num_obj)</span><br><span class="line">print(nums)</span><br><span class="line"><span class="comment"># [2, 3, 5, 7, 11, 13]</span></span><br></pre></td></tr></table></figure>

<h4 id="保存和读取用户生成的数据"><a href="#保存和读取用户生成的数据" class="headerlink" title="保存和读取用户生成的数据"></a>保存和读取用户生成的数据</h4><p>初次保存：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line">username=input(<span class="string">"What's your name?"</span>)</span><br><span class="line">filename=<span class="string">'username.json'</span></span><br><span class="line"><span class="keyword">with</span> open(filename,<span class="string">'w'</span>) <span class="keyword">as</span> user_obj:</span><br><span class="line">    json.dump(username,user_obj)</span><br><span class="line">    print(<span class="string">"We'll remember you when you come back, "</span>+username+<span class="string">"!"</span>)</span><br></pre></td></tr></table></figure>

<p>数据读取：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line">filename=<span class="string">'username.json'</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    <span class="keyword">with</span> open(filename,<span class="string">'r'</span>) <span class="keyword">as</span> user_obj:</span><br><span class="line">        username=json.load(user_obj)</span><br><span class="line"><span class="keyword">except</span> FileNotFoundError:</span><br><span class="line">    <span class="keyword">with</span> open(filename,<span class="string">'w'</span>) <span class="keyword">as</span> f_obj:</span><br><span class="line">        json.dump(username,f_obj)</span><br><span class="line">        print(<span class="string">"We'll remember you when you come back, "</span> + username + <span class="string">"!"</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">        print(<span class="string">"welcome back, &#123;&#125; !"</span>.format(username))</span><br><span class="line"><span class="comment"># 优化了交互</span></span><br></pre></td></tr></table></figure>

<h4 id="重构"><a href="#重构" class="headerlink" title="重构"></a>重构</h4><p>代码可以正确运行，但是可以做进一步的改进——将代码划分为一些列完成具体工作的函数，这样的过程称为重构。让代码更清晰，易于理解、容易扩展。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_stored_username</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""如果用户存储了用户名，就获取它"""</span></span><br><span class="line">    filename=<span class="string">'username.json'</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">with</span> open(filename) <span class="keyword">as</span> f_obj:</span><br><span class="line">            username=json.load(f_obj)</span><br><span class="line">    <span class="keyword">except</span> FileNotFoundError:</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> username</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">greet_user</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""问候用户，并指出其名字"""</span></span><br><span class="line">    username=get_stored_username()</span><br><span class="line">    <span class="keyword">if</span> username:</span><br><span class="line">        print(<span class="string">"欢迎回来，&#123;&#125;！"</span>.format(username))</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        username = get_new_username()</span><br><span class="line">        print(<span class="string">"我们记住你了，欢迎你的下次到来,&#123;&#125;"</span>.f ormat(username))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_new_username</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""获取用户的名字"""</span></span><br><span class="line">    username = input(<span class="string">"请输入你的名字："</span>)</span><br><span class="line">    filename = <span class="string">'username.json'</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'w'</span>) <span class="keyword">as</span> f_obj:</span><br><span class="line">        json.dump(username, f_obj)</span><br><span class="line">    <span class="keyword">return</span> username</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">greet_user()</span><br></pre></td></tr></table></figure>

<h2 id="测试代码"><a href="#测试代码" class="headerlink" title="测试代码"></a>测试代码</h2><h3 id="测试函数"><a href="#测试函数" class="headerlink" title="测试函数"></a>测试函数</h3><p>name_function.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_formatted_name</span><span class="params">(first, last)</span>:</span></span><br><span class="line">    <span class="string">"""Generate a neatly formatted full name.(生成格式整齐的全名)"""</span></span><br><span class="line">    full_name = first + <span class="string">' '</span> + last</span><br><span class="line">    <span class="keyword">return</span> full_name.title()</span><br></pre></td></tr></table></figure>

<p>names.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> name_function <span class="keyword">import</span> get_formatted_name</span><br><span class="line"></span><br><span class="line">print(<span class="string">"输入q可在任意时间退出"</span>)</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    first = input(<span class="string">"请输入你的姓氏："</span>)</span><br><span class="line">    <span class="keyword">if</span> first == <span class="string">'q'</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">        <span class="comment"># 输入q会把first内容改掉</span></span><br><span class="line">    last = input(<span class="string">"请输入你的名："</span>)</span><br><span class="line">    <span class="keyword">if</span> last == <span class="string">'q'</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">formatted_name = get_formatted_name(first, last)</span><br><span class="line">print(<span class="string">"整齐的格式：&#123;&#125;"</span>.format(formatted_name))</span><br></pre></td></tr></table></figure>

<h4 id="可通过的测试"><a href="#可通过的测试" class="headerlink" title="可通过的测试"></a>可通过的测试</h4><p>创建测试的语法需要一段时间才能习惯，但测试用例创建后，再添加针对函数的单元测试就很简单了。先导入unittest模块，再创建一个继承unittest.TestCase的类，并编写一系列方法对函数行为的不同方面进行测试。</p>
<p>测试用例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> unittest</span><br><span class="line"><span class="keyword">from</span> name_function <span class="keyword">import</span> get_formatted_name</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># testcase,n,测试用例</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NamesTestCase</span><span class="params">(unittest.TestCase)</span>:</span></span><br><span class="line">    <span class="string">"""测试name_function.py"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">test_first_last_name</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""能够正确处理像Janis Joplin这样的姓名吗？"""</span></span><br><span class="line">        formatted_name=get_formatted_name(<span class="string">'janis'</span>,<span class="string">'joplin'</span>)</span><br><span class="line">        self.assertEqual(formatted_name,<span class="string">'Janis Joplin'</span>)</span><br><span class="line">unittest.main()</span><br></pre></td></tr></table></figure>

<p>首先我们导入了模块unittest和要测试的函数。我们创建了一个名为NamesTestCase的类，用于包含一系列针对get_formatted_name()的单元测试。可以随便给这个类命名，最好看起来相关。</p>
<p>NamesTestCase只包含一个方法，用于测试get_formatted_name()的一个方面。我们将这个方法命名为test_first_last_name()，因为我们要核实的是只有名和姓的姓名能否被正确的格式化。我们运行test_name_function.py时，所有以test_打头得方法都将自动运行。在这个方法中，我们调用了要测试的函数，病存储了要测试的返回值。在这个示例中，我们使用实参’janis’和’joplin’调用get_formatted_name()，并将结果存储到变量formatted_name中。</p>
<p>我们使用了unittest类最有用的功能之一：<strong>一个断言方法</strong>。断言方法用来核实得到的结果是否与期望的结果一致。在这里，我们知道get_formatted_name()应该返回这样的姓名，及名和姓首字母大写，而且中间有空格，因此我们期望formatted_name的值为Janis Joplin。为了检查是否确实如此，我们调用了unittest的方法assertEqual() ，并向它传递formatted_name和’Janis Joplin’。代码行self.assertEqual(formatted_name,’Janis Joplin’)的意思是说：“将formatted_name的值同字符串’Janis Joplin’进行比较，如果他们相等，就万事大吉。如果它们不相等，跟我说一声！”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># .</span></span><br><span class="line"><span class="comment"># -----------------------------------------------------</span></span><br><span class="line"><span class="comment"># Ran 1 test in 0.000s</span></span><br><span class="line"><span class="comment"># </span></span><br><span class="line"><span class="comment"># OK</span></span><br></pre></td></tr></table></figure>

<p>第一行的句点表明有一个测试通过了。加下来的一行指出运行了一个测试，消耗的时间不到0.001秒。最后的OK表明该测试用例中的所有单元测试都通过了。</p>
<h4 id="测试未通过时怎么办"><a href="#测试未通过时怎么办" class="headerlink" title="测试未通过时怎么办"></a>测试未通过时怎么办</h4><p>不要修改测试，而应该修复导致测试不能通过的代码</p>
<h4 id="添加新测试"><a href="#添加新测试" class="headerlink" title="添加新测试"></a>添加新测试</h4><p>确定get_formatted_name() 又能够正确地处理简单的姓名后，我们再编写一个测试，用于测试中间名。我们在NamesTestCase类中再添加一个方法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_first_last_middle_name</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""能够正确处理向Wolfgang Amadeus Mozart这样的姓名吗？"""</span></span><br><span class="line">    formatted_name = get_formatted_name(<span class="string">'wolfgang'</span>, <span class="string">'mozart'</span>, <span class="string">'amadeus'</span>)</span><br><span class="line">    self.assertEqual(formatted_name, <span class="string">'Wolfgang Amadeus Mozart'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h3><h4 id="各种断言方法"><a href="#各种断言方法" class="headerlink" title="各种断言方法"></a>各种断言方法</h4><p>你只能在继承unittest.TestCase的类中使用这些方法</p>
<p>百度后自己背诵吧。</p>
<h4 id="一个要测试的类"><a href="#一个要测试的类" class="headerlink" title="一个要测试的类"></a>一个要测试的类</h4><p>单纯的编写一个类，还没有开始测试呢</p>
<p>survey.py：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AnonymousSurvey</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">"""收集匿名调查问卷的答案"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, question)</span>:</span></span><br><span class="line">        self.question = question</span><br><span class="line">        self.responses = []</span><br><span class="line">        <span class="comment"># 有必要再看一遍类里面的方法是用什么样的变量，带不带self？带</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_question</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""显示调查问卷"""</span></span><br><span class="line">        print(self.question)</span><br><span class="line">    <span class="comment">#     有必要再看一遍，这里竟然需要写self，访问类中初始化的变量需要写self，访问当前函数自己定义的变量则不需要写self</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">store_response</span><span class="params">(self,new_response)</span>:</span></span><br><span class="line">        <span class="string">"""存储单份调查问卷"""</span></span><br><span class="line">        self.responses.append(new_response)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_results</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""显示收集到的所有答卷"""</span></span><br><span class="line">        print(<span class="string">"调查结果反馈："</span>)</span><br><span class="line">        <span class="keyword">for</span> response <span class="keyword">in</span> self.responses:</span><br><span class="line">            print(<span class="string">"- "</span>+ response)</span><br></pre></td></tr></table></figure>

<p>language_survey.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> survey <span class="keyword">import</span> AnonymousSurvey</span><br><span class="line"><span class="comment"># 定义一个问题，并创建一个表示匿名调查表的对象</span></span><br><span class="line">question=<span class="string">"你第一个学会说的语言是什么?"</span></span><br><span class="line">my_survey=AnonymousSurvey(question)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 显示问题并存储答案</span></span><br><span class="line">my_survey.show_question()</span><br><span class="line">print(<span class="string">"输入q来结束调查。"</span>)</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    response=input(<span class="string">"Language: "</span>)</span><br><span class="line">    <span class="keyword">if</span> response==<span class="string">'q'</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    my_survey.store_response(response)</span><br><span class="line"><span class="comment"># 显示调查结果</span></span><br><span class="line">print(<span class="string">"感谢参与调查的人员！"</span>)</span><br><span class="line">my_survey.show_results()</span><br></pre></td></tr></table></figure>

<h4 id="测试这个AnonymousSurvey类"><a href="#测试这个AnonymousSurvey类" class="headerlink" title="测试这个AnonymousSurvey类"></a>测试这个AnonymousSurvey类</h4><p>测试单个答案是否会被保存</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> unittest</span><br><span class="line"><span class="keyword">from</span> survey <span class="keyword">import</span> AnonymousSurvey</span><br><span class="line"><span class="comment"># store,v,贮存，存储，记忆</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestAnonymousSurvey</span><span class="params">(unittest.TestCase)</span>:</span></span><br><span class="line">    <span class="string">"""针对AnonymousSurvey类的测试"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">test_store_single_response</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""测试单个答案，是否会被妥善存储"""</span></span><br><span class="line">        question = <span class="string">"你第一次学着去说的是什么语言？ "</span></span><br><span class="line">        my_surver = AnonymousSurvey(question)</span><br><span class="line">        <span class="comment"># 实例化并初始化数据</span></span><br><span class="line">        my_surver.store_response(<span class="string">'English'</span>)</span><br><span class="line">        <span class="comment"># 调用方法，传输数据</span></span><br><span class="line">        self.assertIn(<span class="string">'English'</span>, my_surver.responses)</span><br><span class="line">        <span class="comment"># 测试是否函数获得了English并将其存了起来，参数是元素和列表</span></span><br><span class="line">unittest.main()</span><br></pre></td></tr></table></figure>

<p>测试一个答案的用途不大，我们测试三个：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> unittest</span><br><span class="line"><span class="keyword">from</span> survey <span class="keyword">import</span> AnonymousSurvey</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># store,v,贮存，存储，记忆</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestAnonymousSurvey</span><span class="params">(unittest.TestCase)</span>:</span></span><br><span class="line">    <span class="string">"""针对AnonymousSurvey类的测试"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">test_store_single_response</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""测试单个答案，是否会被妥善存储"""</span></span><br><span class="line">        question = <span class="string">"你第一次学着去说的是什么语言？ "</span></span><br><span class="line">        my_surver = AnonymousSurvey(question)</span><br><span class="line">        <span class="comment"># 实例化并初始化数据</span></span><br><span class="line">        my_surver.store_response(<span class="string">'English'</span>)</span><br><span class="line">        <span class="comment"># 调用方法，传输数据</span></span><br><span class="line">        self.assertIn(<span class="string">'English'</span>, my_surver.responses)</span><br><span class="line">        <span class="comment"># 测试是否函数获得了English并将其存了起来，参数是元素和列表</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">test_store_three_response</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""测试三个答案是否会被妥善保存"""</span></span><br><span class="line">        question = <span class="string">"你第一次学着去说的是什么语言？ "</span></span><br><span class="line">        my_surver = AnonymousSurvey(question)</span><br><span class="line">        responses = [<span class="string">'English'</span>, <span class="string">'Chinese'</span>, <span class="string">'Japanese'</span>]</span><br><span class="line">        <span class="comment"># 虽然匿名调查表类里有同名变量，但是这个并不是匿名调查表类的属性</span></span><br><span class="line">        <span class="keyword">for</span> response <span class="keyword">in</span> responses:</span><br><span class="line">            my_surver.store_response(response)</span><br><span class="line">        <span class="keyword">for</span> response <span class="keyword">in</span> responses:</span><br><span class="line">            <span class="comment"># 循环断言验证是否存在</span></span><br><span class="line">            self.assertIn(response, my_surver.responses)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">unittest.main()</span><br></pre></td></tr></table></figure>

<p>主要思想就是，事先设置好可能的数据，然后推测期望并验证是否一致。无论是类还是方法，均可以通过这种方式快速的找出错误。</p>
<h4 id="unittest的另一项功能，方法setUp"><a href="#unittest的另一项功能，方法setUp" class="headerlink" title="unittest的另一项功能，方法setUp()"></a>unittest的另一项功能，方法setUp()</h4><p>这个方法的优先级高于test_打头的方法，所以Python会先运行它。</p>
<p>下面使用setUp() 来创建一个调查对象和一组答案，供方法test_store_single_response() 和 test_store_three_response() 使用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> unittest</span><br><span class="line"><span class="keyword">from</span> survey <span class="keyword">import</span> AnonymousSurvey</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># store,v,贮存，存储，记忆</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestAnonymousSurvey</span><span class="params">(unittest.TestCase)</span>:</span></span><br><span class="line">    <span class="string">"""针对AnonymousSurvey类的测试"""</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setUp</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""创建一个调查对象和一组答案，供使用测试的方法使用"""</span></span><br><span class="line">        question = <span class="string">"你学了些什么玩意儿？"</span></span><br><span class="line">        self.my_survey = AnonymousSurvey(question)</span><br><span class="line">        <span class="comment"># 自身定义一个用来存储匿名调查表实例的变量</span></span><br><span class="line">        self.responses = [<span class="string">'English'</span>, <span class="string">'Chinese'</span>, <span class="string">'Japanese'</span>]</span><br><span class="line">        <span class="comment"># 这个是用于测试的responses列表，是测试类的属性，而不是匿名调查表类的属性</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">test_store_single_response</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""测试单个答案，是否会被妥善存储"""</span></span><br><span class="line">        self.my_survey.store_response(self.responses[<span class="number">0</span>])</span><br><span class="line">        self.assertIn(<span class="string">'English'</span>, self.my_survey.responses)</span><br><span class="line">        <span class="comment"># 这一句看起来是访问了自身的my_survey（匿名调查表的一个实例），之后又访问了它的responses属性</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">test_store_three_response</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""测试三个答案是否会被妥善保存"""</span></span><br><span class="line">        <span class="comment"># 这里的responses来自第十六行的当前类之下的定义，区别于匿名调查表中的同名属性</span></span><br><span class="line">        <span class="keyword">for</span> response <span class="keyword">in</span> self.responses:</span><br><span class="line">            self.my_survey.store_response(response)</span><br><span class="line">        <span class="keyword">for</span> response <span class="keyword">in</span> self.responses:</span><br><span class="line">            <span class="comment"># 循环断言验证是否存在</span></span><br><span class="line">            self.assertIn(response, self.my_survey.responses)</span><br><span class="line">        <span class="comment"># 大概就是自身建立了一套初始化的体系，同一类下的所有方法可使用self句点表示法来访问</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">unittest.main()</span><br></pre></td></tr></table></figure>

<p>测试自己编写的类时，方法setUp() 让测试方法编写起来更容易：可在setUp() 方法中创建一系列实例并设置他们的属性。再在测试方法中直接使用这些实例。相比于在每个测试方法中都创建实例并设置其属性，这显然要容易得多。</p>
<p><strong>注意：</strong></p>
<ol>
<li>每完成一个单元测试，Python都打印一个字符，通过打印句点。</li>
<li>引发错误时打印一个E</li>
<li>断言失败时打印一个F</li>
</ol>
<h4 id="小结-2"><a href="#小结-2" class="headerlink" title="小结"></a>小结</h4><p>单元测试用于核实函数的某个方面没有问题，测试用例是一组单元测试，尽量考虑周到。全覆盖式测试包含一整套单元测试，涵盖了可能的函数使用方式。</p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    Last updated: <time datetime="2020-07-29T05:45:35.549Z" itemprop="dateUpdated">2020-07-29 13:45:35</time>
</span><br>


        
        这里可以写作者留言，标签和 hexo 中所有变量及辅助函数等均可调用，示例：<a href="/blog/2020/07/10/PythonBook/" target="_blank" rel="external">https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/</a>
        
    </div>
    
    <footer>
        <a href="https://gitee.com/songbug/blog.git">
            <img src="/blog/img/avatar.jpg" alt="Song Wani">
            Song Wani
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/%E7%AC%94%E8%AE%B0/" rel="tag">笔记</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/&title=《Python啃书笔记》 — SongKaBaKa&pic=https://gitee.com/songbug/blog.git/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/&title=《Python啃书笔记》 — SongKaBaKa&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Python啃书笔记》 — SongKaBaKa&url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/&via=https://gitee.com/songbug/blog.git" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/2020/07/10/%E5%AD%97%E5%85%B8%E4%B8%AD%E5%AD%98%E5%82%A8%E5%88%97%E8%A1%A8%E5%8F%8A%E5%A4%9A%E5%8F%98%E9%87%8Ffor-in%E5%BE%AA%E7%8E%AF/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">字典中存储列表及多变量for-in循环</h4>
      </a>
    </div>
  

  
</nav>



    




















</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/blog/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/blog/img/wechat.jpg" data-alipay="/blog/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
            <span>This blog is licensed under a <a rel="license noopener" href="https://creativecommons.org/licenses/by/4.0/" target="_blank">Creative Commons Attribution 4.0 International License</a>.</span>
        </p>
    </div>
    <div class="bottom">
        <p><span>Song Wani &copy; 2019 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/&title=《Python啃书笔记》 — SongKaBaKa&pic=https://gitee.com/songbug/blog.git/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/&title=《Python啃书笔记》 — SongKaBaKa&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Python啃书笔记》 — SongKaBaKa&url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/&via=https://gitee.com/songbug/blog.git" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://gitee.com/songbug/blog.git/2020/07/10/PythonBook/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
